ASP MVC 5属性路由未注册路由

本文关键字:路由 注册 属性 MVC ASP | 更新日期: 2023-09-27 18:21:00

概述

我目前正在尝试让属性路由与我的api控制器一起工作。它似乎不起作用,我不确定为什么。我不确定我是否错过了关键的一步,或者问题可能是什么

问题

我正在尝试访问localhost/api/user/custom?test=1但我得到了404(我希望这能起作用)

如果我点击localhost/api/customapi?test=1我成功地进入了我的方法

为什么第一个url不起作用?

设置

我的设置如下:

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);
    }
}

ASP MVC 5属性路由未注册路由

我在路由中使用了错误的命名空间。

[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")]