【问题标题】:MVC5 Attribute Routing in WebApi spaceWeb Api 空间中的 MVC 5 属性路由
【发布时间】:2015-06-21 17:31:57
【问题描述】:

我正在使用 MVC 控制器在 Web Api 项目中创建动态 JavaScript 文件(我对此部分不满意,但我正在尝试保持与以前版本的兼容性)...

客户端正在使用如下 URL:

~/api/assessments/{id:int}.js?locale={locale?}

我创建了一个 MVC JavaScriptController 并添加了这样的方法:

    [Route("~/api/data/{id:int}.js")]
    public async Task<PartialViewResult> GetData(int id, string locale)
    {
        try
        {
            Response.ContentType = "application/javascript";
            ViewBag.Locale = locale ?? "en";
            var model = await this._dataService.GetData(id.ToString());
            return PartialView(model);
        }
        catch (Exception ex)
        {
            this._logger.Error("Task<PartialViewResult> GetData(int, string)", ex);
            return PartialView("JavaScriptError", SelectException(ex));
        }
    }

但是,当我尝试调用此调用时,我得到了 404:

<Error>
    <Message>
        No HTTP resource was found that matches the request URI 'http://.../api/data/29.js?locale=en'.
    </Message>
    <MessageDetail>
        No type was found that matches the controller named 'data'.
    </MessageDetail>
</Error>

我认为 WebApi "~/api" 前缀正在踩着 MVC 5 路线,尽管我认为它可能是完全不同的东西。如何在指定的 URL 处呈现此 MVC 视图?

【问题讨论】:

  • Route 属性的命名空间是什么?
  • 我没有指定一个。
  • 确保它是System.Web.Http.RouteAttribute 而不是System.Web.Mvc.RouteAttribute
  • @haim770,这似乎没有什么不同。

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


【解决方案1】:

您不需要在路由中包含查询字符串参数或相对路径:

    [Route("api/data/{id:int}.js")]
    protected async Task<PartialViewResult> GetData(int id, string locale)
    {
        try
        {
            Response.ContentType = "application/javascript";
            ViewBag.Locale = locale ?? "en";
            var model = await this._dataService.GetData(id.ToString());
            return PartialView(model);
        }
        catch (Exception ex)
        {
            this._logger.Error("Task<PartialViewResult> GetData(int, string)", ex);
            return PartialView("JavaScriptError", SelectException(ex));
        }
    }

由于实际上只对 API 的特定部分(“文件”的名称)进行了模板化,因此您只需将其作为路由的一部分。

但是,您仍然会遇到 .NET 尝试将 .js 请求视为文件请求的问题。

为此,您可能必须启用relaxed filesystem mapping

<httpRuntime relaxedUrlToFileSystemMapping="true" />

但是,您确实需要注意 security implications 启用此功能。如果您没有正确设置 NTFS 权限,您将面临潜在的攻击,远程用户可以访问您文件系统上的文件。

【讨论】:

  • 嗯,输入有意义,但这似乎没有什么区别。
【解决方案2】:

您在路线注册期间是否致电MapHttpAttributeRoutes()

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#why

【讨论】:

    【解决方案3】:

    好吧,看来我是对的; WebApi 路由机制基于 MVC 属性路由。最后,我不得不在我的WebApiConfig.cs 文件中注释掉以下行:

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

    之后,MVC 路由按预期工作。

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 2013-10-28
      • 2017-12-20
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多