我花了相当多的时间试图让Web API属性路由工作,而我得到的只是404错误,无论我尝试什么.
我有一个简单的ApiController尝试在api / hello / {number}和hello / {number}定义一个HttpGet:
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; } }
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 } ); } }
WebAPIConfig:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); } }
最后,这是我的Application_Start(),我注册了WebApiConfig:
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
我的帖子也不起作用.