我遵循了一些答案,但在邮递员身上得到以下错误
{
"Message": "The requested resource does not support http method 'GET'."
}
这些是我跟随的链接
How to add custom methods to ASP.NET WebAPI controller?
目前的设置类似于sky-dev描述的那个
Custom method names in ASP.NET Web API
已更新为代码
webapiconfig.cs
public static void Register(HttpConfiguration config)
{
// 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 }
//);
config.Routes.MapHttpRoute("DefaultApiWithId", "api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}");
config.Routes.MapHttpRoute(name: "ApiWithActionName",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
}
defaultcontroller.cs
public class DefaultController : ApiController
{
DBEntities db = new DBEntities();
public IEnumerable<CategoryDTO> Category()
{
IEnumerable<CategoryDTO> List = from tr in db.Categories
where tr.IsActive == "Y"
orderby tr.DisplayOrder ascending
select new CategoryDTO()
{
Id = tr.Id,
Name = tr.Name
};
return List;
}
// GET: api/Default
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Default/5
public string Get(int id)
{
return "value";
}
// POST: api/Default
public void Post([FromBody]string value)
{
}
// PUT: api/Default/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Default/5
public void Delete(int id)
{
}
}
答案 0 :(得分:0)
如果您使用的是web api 2,则可以使用“属性路由” 请关注此网址,希望您能得到答案
样品:
[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
要了解更多详细信息,请点击此链接 http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
还有另一种方法可以通过在WebApiConfig.cs中编写自己的路径来使用自定义方法 你可以在这个链接中找到这个细节 http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
希望这会对你有所帮助。