概述
我目前正在尝试使属性路由与我的api控制器一起工作。它似乎不起作用,我也不知道为什么。我不知道我是不是错过了关键的一步,或者问题出在哪里。
问题
我正在尝试点击localhost/api/user/custom?test=1,但我得到了404 (我希望这个能工作)
如果我点击localhost/api/customapi?test=1,我就成功地进入了我的方法
为什么第一个网址不起作用?
设置
我的设置如下:
CustomController.cs
[System.Web.Mvc.RoutePrefix("api")]
public class CustomApiController : ApiController
{
[System.Web.Mvc.Route("user/custom")]
[System.Web.Http.HttpGet]
public async Task<CustomResponse> Get([FromUri] CustomRequest request)
{
//Work
}
}WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...(json serializer settings)...
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}RouteConfig.cs
public static class RouteConfig
{
public static void Register(RouteCollection routes, bool registerAreas = true)
{
if(registerAreas)
{
AreaRegistration.RegisterAllAreas();
}
//Ignore Routes
...
//Register specific routes
routes.MapRoute("HomeUrl", "home", new { controller = "Home", action = "Index" });
.
.
routes.MapRoute(
"Default", //Route name
"{controller}/{action}/{id}", //URL with parameters
new { controller = "Home", action = "Index", id =UrlParameter.Optional }
);
}
} Global.asax.cs
public class Global : HttpApplication
{
protected void Application_Start()
{
....(app startup stuff)...
GlobalConfiguration.Configure(WebApiConfig.Register);
BundleConfig.Register(BundleTable.Bundles);
....(more app startup stuff)...
RouteConfig.Register(RouteTable.Routes);
}
}发布于 2014-09-08 16:32:28
我在路由中使用了错误的命名空间。
[System.Web.Http.Route("")] //Use this namespace for Web API 2
[System.Web.Mvc.Route("")]
[System.Web.Http.RoutePrefix("api")] //Use this namespace Web API 2
[System.Web.Mvc.RoutePrefix("api")]https://stackoverflow.com/questions/25727305
复制相似问题