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

标签 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 这样的操作,以便模板得到 login.html 作为文件传递姓名。

但我总是得到:找不到与请求 URI“http://localhost:50121/api/admin/template/login.html”匹配的 HTTP 资源

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

有人知道我的路由有什么问题吗?

编辑:

我的路线配置

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

最佳答案

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

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

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

参见 MSDN

关于c# - ASP.net web api 2 路由属性不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28067419/

相关文章:

c# - 如何从 C# Core 中的 DI 获取可用的 IOptions 列表?

c# - 从 Web API 帮助页面中排除媒体类型示例

c# - 需要 .NET 串行端口帮助,主要是在多个 "packets"中接收到的数据

c# - 将逗号分隔的列表绑定(bind)到 asp.net web api 中的 List<int>

c# - 如何在 ASP.NET Web API 上获取对象?

c# - 在属性中使用 .Add() 方法添加元素后,list.Count 为零

c# - 接口(interface)声明和通用约束

.NET Windows服务需要使用STAThread

.net - 将 1.1 框架升级到 4.0

javascript - Knockoutjs 将 observableArray 绑定(bind)到 byte