首页 > 解决方案 > 带有字符串 id 的 ASP WebApi GET 响应?

问题描述

我有个问题。

我有一张用户表。用户 ID 为string. 我的 GET 看起来像这样:

    // GET: api/WatchedProduct
    [HttpGet]
    public IEnumerable<WatchedProduct> GetWatchedProduct(string id)
    {
        var productsList = id == String.Empty ?
            db.WatchedProducts.Where(u => u.ApplicationUserId == id).ToList() :
            db.WatchedProducts.Where(u => u.ApplicationUserId == loggedUserId).ToList();

        return productsList;
    }

当我在 Postman 中调用 API 时,我得到以下响应:

{
"message": "No HTTP resource was found that matches the request URI 'http://.../api/WatchedProduct'.",
"messageDetail": "No action was found on the controller 'WatchedProduct' that matches the request."
}

我的问题是,如何制作GetWatchedProduct类似 when idis int( GetWatchedProduct(int? id)) 的方法?是否可以对字符串做同样的事情?我需要另一个 Get 方法吗?

编辑:

当我使用字符串参数调用我的 API 时:

http://localhost.../api/WatchedProduct/StringidHere

它有效,我想在我的控制器中有一种 GET 方法。我何时String.Empty何地传递一个字符串。

我的RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();
        //AreaRegistration.RegisterAllAreas();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

编辑2

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        /*var cors = new EnableCorsAttribute("http://localhost:4200", "*", "GET,POST,PUT,DELETE,OPTIONS");
        cors.SupportsCredentials = true;

        config.EnableCors(cors);*/

        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

编辑3:

例如,来自另一个控制器的该方法有效:

     // GET: api/Product/search?str=kaarol
    [Route("search")]
    public IEnumerable<Product> GetSearch(string str)
    {
        return db.Products.Where(p => p.Name.Contains(str)).ToList();
    }

但就我而言,我希望有一种方法可以在我想调用/Api/Watched...StringID时候调用。

标签: c#asp.net-mvclinqasp.net-web-api

解决方案


通常,您的路线的工作方式类似于GET /api/controllerName/如果您想访问它,就像GET /api/controllerName/customRoute您需要路由您的方法一样。

// GET: api/WatchedProduct
[HttpGet]
[Route("WatchedProduct")]
public IEnumerable<WatchedProduct> GetWatchedProduct(string id)
{
    var productsList = id == String.Empty ?
        db.WatchedProducts.Where(u => u.ApplicationUserId == id).ToList() :
        db.WatchedProducts.Where(u => u.ApplicationUserId == loggedUserId).ToList();

    return productsList;
}

更多信息微软文档在这里

编辑

如果您的控制器名称是,WatchedProductController那么您不需要明确指定它。我要说的是:

public class WatchedProduct : ApiController
{
    // GET: api/WatchedProduct
    [HttpGet]
    public IEnumerable<WatchedProduct> Get(string id)
    {
        var productsList = id == String.Empty ?
        db.WatchedProducts.Where(u => u.ApplicationUserId == id).ToList() :
        db.WatchedProducts.Where(u => u.ApplicationUserId == loggedUserId).ToList();

        return productsList;
    }
}

应该有效。


推荐阅读