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

Ben*_*dEg 4 .net c# routing asp.net-web-api

我有以下问题,我的路由属性不起作用.

我有以下行动:

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

我想访问类似的操作.../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 });
Run Code Online (Sandbox Code Playgroud)

小智 6

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


hai*_*770 5

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

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

        // you can add manual routes as well
        //config.Routes.MapHttpRoute(...
    }
}
Run Code Online (Sandbox Code Playgroud)

参见MSDN

  • @leen3o,见 http://www.asp.net/web-api/overview/advanced/configuring-aspnet-web-api (2认同)

Cem*_*tlu 5

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