我有一个用户表。用户的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