代码之家  ›  专栏  ›  技术社区  ›  michasaucer

ASP WebApi是否获取字符串id为的响应?

  •  0
  • michasaucer  · 技术社区  · 7 年前

    我有一个用户表。用户的ID是一个 string . 我得到的结果是这样的:

        // 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 id 是 int ( GetWatchedProduct(int? id) ) ? 可以对字符串执行同样的操作吗?我需要另一种获取方法吗?

    使用字符串param调用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

    2 回复  |  直到 7 年前
        1
  •  4
  •   Community Mohan Dere    6 年前

    通常你的路线是这样的 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;
    }
    

    更多信息 Microsoft docs here

    编辑

    如果您的控制器名称为 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;
        }
    }
    

        2
  •  0
  •   Gurpreet_Carmel_5    7 年前

    你可以试试这样的

    public class WatchedProduct : ApiController
    {
     // GET: api/WatchedProduct
     [HttpGet]
      [Route("WatchedProduct")]
       public IEnumerable<WatchedProduct> Get()
      {
       var context = Request.Properties["MS_HttpContext"] as HttpContext;
       var id = context.Request.QueryString["id"];
        var productsList = id == String.Empty ?
        db.WatchedProducts.Where(u => u.ApplicationUserId == id).ToList() :
        db.WatchedProducts.Where(u => u.ApplicationUserId == loggedUserId).ToList();
    
        return productsList;
      }
    }
    

    应适用于两种情况,因为它满足两种路线。