ASP.net web api 2 Route-Attribute not working

前端 未结 7 1876
野性不改
野性不改 2021-01-19 17:52

I\'ve the following problem, my route attribute is not working.

I have the following action:

[HttpGet]
[Route(\"~api/admin/template/{fileName}\")]
pu         


        
相关标签:
7条回答
  • 2021-01-19 18:26

    In my case, I added Route("api/dashboard") to api controller. Changed it to RoutePrefix("api/dashboard") . And it works perfectly. Also you need config.MapHttpAttributeRoutes(); in webapiconfig.cs

    0 讨论(0)
  • 2021-01-19 18:33

    With my Web API 2 project I had to add a [RoutePrefix("events")] to the controller for it to pickup the action route attribute.

    0 讨论(0)
  • 2021-01-19 18:38

    You have to call MapHttpAttributeRoutes() so that the Framework will be able to walk through your attributes and register the appropriate routes upon application start:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
    
            // you can add manual routes as well
            //config.Routes.MapHttpRoute(...
        }
    }
    

    See MSDN

    0 讨论(0)
  • 2021-01-19 18:46
    try adding a forward slash after the tilde
    [HttpGet]
    [Route("~/api/admin/template/{fileName}")]
    public HttpResponseMessage Template(string fileName)
    {
        return CreateHtmlResponse(fileName);
    }
    
    0 讨论(0)
  • 2021-01-19 18:46

    Check your Route attribute's namespace. It should be System.Web.Http instead of System.Web.Mvc.

    0 讨论(0)
  • 2021-01-19 18:46

    Try this routing in your WebApiConfig

            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    

    You have to add RoutePrefix.

    0 讨论(0)
提交回复
热议问题