ASP.net web api 2 Route-Attribute无法正常工作

时间:2015-01-21 12:36:04

标签: c# .net asp.net-web-api routing

我遇到以下问题,我的路线属性无效。

我有以下行动:

[HttpGet]
[Route("~api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
    return CreateHtmlResponse(fileName);
}

我希望访问.../api/admin/template/login.html之类的操作,以便将模板get login.html 作为文件名传递。

但我总是得到:No HTTP resource was found that matches the request URI 'http://localhost:50121/api/admin/template/login.html'

以下请求有效:/api/admin/template?fileName=login.html

有谁知道,我的路由错误了什么?

修改

我的路线配置

config.Routes.MapHttpRoute(
                    "API Default", "api/{controller}/{action}",
                    new { id = RouteParameter.Optional });

7 个答案:

答案 0 :(得分:6)

try adding a forward slash after the tilde
[HttpGet]
[Route("~/api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
    return CreateHtmlResponse(fileName);
}

答案 1 :(得分:5)

检查Route属性的命名空间。它应该是 System.Web.Http 而不是 System.Web.Mvc

答案 2 :(得分:4)

您必须调用MapHttpAttributeRoutes(),以便框架能够遍历您的属性并在应用程序启动时注册适当的路由:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        // you can add manual routes as well
        //config.Routes.MapHttpRoute(...
    }
}

请参阅MSDN

答案 3 :(得分:2)

确定您使用的是System.Web.Http.RouteAttribute而非System.Web.Mvc.RouteAttribute

答案 4 :(得分:1)

WebApiConfig

中尝试此路由
        // Web API routes
        config.MapHttpAttributeRoutes();

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

您必须添加RoutePrefix

答案 5 :(得分:1)

使用我的Web API 2项目,我不得不向控制器添加[RoutePrefix("events")],以便它获取动作路由属性。

答案 6 :(得分:0)

在我的情况下,我将Route("api/dashboard")添加到a​​pi控制器。 将其更改为RoutePrefix("api/dashboard")。而且效果很好。 您还需要webapiconfig.cs中的config.MapHttpAttributeRoutes();

相关问题