我花了相当多的时间试图让 Web API 属性路由正常工作,无论我尝试什么,我得到的都是 404 错误。
我有一个简单的 ApiController 试图在 api/hello/{number}
定义一个 HttpGet和 hello/{number}
:
public class HelloController : ApiController
{
public class Hello
{
public string user { get; set; }
public string password { get; set; }
}
[Route("api/hello/{number}")]
[Route("hello/{number}")]
[HttpGet]
public IEnumerable<Hello> GetStuff(int number)
{
var response = Request.CreateResponse(HttpStatusCode.Created, number);
return null;
}
[Route("api/hello")]
[HttpPost]
public HttpResponseMessage PostHello(Hello value)
{
var response = Request.CreateResponse(HttpStatusCode.Created, value);
return response;
}
}
我将此作为我的 RouteConfig,启用属性路由:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
WebAPI 配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
}
}
最后,这是我注册 WebApiConfig 的 Application_Start():
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
有没有人看到我想念的东西?对于以下所有情况,我收到 404 错误(无法在 GetStuff() 中找到断点):
http://localhost/api/hello
http://localhost/api/hello/1
http://localhost/hello
http://localhost/hello/2
我的帖子也不起作用。
最佳答案
您的 MVC 路由优先于 API 路由。因为您在 MVC 端使用了一个 catch all 路由( "{controller}/{action}/{id}"
),并且它首先被注册,所以您的路由将始终寻找一个名为 api
的 mvc Controller 。或 hello
,因为那是它匹配的路线。
尝试将 api 注册移到 Global.asax 中的 MVC 路由注册上方:
GlobalConfiguration.Configure(WebApiConfig.Register);
//then
RouteConfig.RegisterRoutes(RouteTable.Routes);
关于asp.net - 无法启用/工作的 Web API 属性路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493525/