ASP MVC 5 Attribute routing not registering routes

核能气质少年 提交于 2019-12-23 12:31:04

问题


Overview

I'm currently trying to get attribute routing to work with my api controllers. It doesn't appear to be working, and I'm unsure why. I'm not sure if I'm missing a crucial step, or what the problem could be.

Problem

I'm trying to hit localhost/api/user/custom?test=1 but I get a 404 (I expect this to work)

If I hit localhost/api/customapi?test=1 I successfully get into my method

Why does the first url not work?

Setup

My setup is as follows:

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

回答1:


I was using the wrong namespace in my routes.

[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/asp-mvc-5-attribute-routing-not-registering-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!