这是我的Web API项目中路由的Register方法
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "AllRoutes",
routeTemplate: "{*url}",
defaults: new { controller = "IncomingRequest", action = "ProcessRequest" });
我希望一切都能在我的IncomingRequest控制器上运行我的ProcessRequest方法。但是所有路线都会产生404.例如
http://localhost/CatCatcher/Cat/3
有人可以告诉我可能错过的内容吗?
答案 0 :(得分:0)
试试这个:
routes.MapRoute(
"AllRoutes",
"{*id}",
new { controller = "IncomingRequest", action = "ProcessRequest", id = "" }
);
对不起,我现在测试了它......
答案 1 :(得分:0)
在Web API项目中,您无法通过不同的方式设置路由,如:
config.Routes.MapHttpRoute(
name: "Routes",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
要实现URL(“http://localhost/CatCatcher/Cat/3”),您可以在控制器和操作上设置路由前缀。以下是示例:
[RoutePrefix("CatCatcher")]
public class CatCatcherController : ApiController
{
[HttpGet]
[Route("Cat")]
public object Cat(int Id){
//Do something
}
}
如果你想在点击Action之前继续执行,那么让我们按照我用IP / Domain保护API的例子来说:
public class AuthorizeIPAddressAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext filterContext)
{
//Even you can do here what you want
//Get users IP Address
string ipAddress = HttpContext.Current.Request.UserHostAddress;
if (!IsIpAddressValid(ipAddress.Trim()))//check allow ip
{
//Send back a HTTP Status code of 403 Forbidden
filterContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
}
base.OnActionExecuting(filterContext);
}
在项目中添加此类后,您只需在控制器上执行此操作:
[AuthorizeIPAddress]
[RoutePrefix("CatCatcher")]
public class CatCatcherController : ApiController
{
[HttpGet]
[Route("Cat")]
public object Cat(int Id){
//Do something
}
}
希望这会对你有帮助..