C# ASP.net web api 2路由属性不工作

C# ASP.net web api 2路由属性不工作,c#,.net,asp.net-web-api,routing,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这样的操作,以便template获得login.html作为文件名传递 但

我有以下问题,我的路由属性不工作

我有以下行动:

[HttpGet]
[Route("~api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
    return CreateHtmlResponse(fileName);
}
我想访问像
../api/admin/template/login.html
这样的操作,以便template获得login.html作为文件名传递

但是我也会得到:
没有找到与请求URI匹配的HTTP资源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 });

在您的
WebApiConfig

        // Web API routes
        config.MapHttpAttributeRoutes();

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

您必须添加
RoutePrefix

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

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

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

请参见

在我的Web API 2项目中,我必须向控制器添加一个
[RoutePrefix(“事件”)]
,以便它拾取操作路由属性

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

在我的例子中,我向api控制器添加了
路由(“api/dashboard”)
。 将其更改为
RoutePrefix(“api/dashboard”)
。而且它工作得很好。
您还需要
config.maphttpAttribute路由()System.Web.Http.RouteAttribute
而不是
System.Web.Mvc.RouteAttribute

是否调用了
config.maphttpAttribute()?@haim770是的,这就是解决方案。如果你创造一个答案,我会接受它,谢谢你!此路由适用于标准MVC控制器,而不是API控制器。@haim770,这实际上是不正确的。。。MapHttpRoute是用于Web Api的。MapRoute是为MVC设计的。@Slick86,请参阅最初的修订版啊,对不起,错过了我不明白这个类的实际名称是什么?@leen3o通常,在您的
Global.asax
中,您如何在Global.asax中调用它?我不明白HttpConfiguration从何而来。@leen3o,请参阅
try adding a forward slash after the tilde
[HttpGet]
[Route("~/api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
    return CreateHtmlResponse(fileName);
}