【问题标题】:Web API 2.2 Content Negotiation with file extensionsWeb API 2.2 带有文件扩展名的内容协商
【发布时间】:2015-01-31 11:08:35
【问题描述】:

我正在开发一个 Web API,我想使用带有文件扩展名的内容协商来允许浏览器客户端指定他们想要接收的内容。比如

http://localhost:54147/data.xslx.  

根据这篇文章 (http://msdn.microsoft.com/en-us/magazine/dn574797.aspx),我应该能够使用类似这样的方式设置路由

//setup default routes
config.Routes.MapHttpRoute(
    name: "Default",
    routeTemplate: "{controller}/{id}",
    defaults: new {id = RouteParameter.Optional}
);

//设置带扩展的路由 config.Routes.MapHttpRoute( name: "网址扩展", routeTemplate: "{controller}/{action}.{ext}/{id}", 默认值:新 { id = RouteParameter.Optional } );

这是我的简单控制器

public class TestController : ApiController
{
    public HttpResponseMessage Get()
    {
        var items = new[] {"test1", "test2", "test3"};
        return Request.CreateResponse(HttpStatusCode.OK, items);
    }
}

使用这个网址

http://localhost:54147/test/get.xlsx 

我总是使用默认浏览器(chrome 中的 xml,IE11 中的 json)。

或者可能

http://localhost:54147/test.xlsx 

我得到错误的地方

No HTTP resource was found that matches the request URI 'http://localhost:54147/test.xlsx'.

我应该能够使用我的自定义格式化程序。但它没有发生。这是我的自定义格式化程序的构造函数。

public ExcelFormatter()
{
    MediaTypeMappings.Add(new UriPathExtensionMapping("xlsx", ContentType.Excel));
    SupportedMediaTypes.Add(new MediaTypeHeaderValue(ContentType.Excel));
}

再次根据文章,这应该有助于 API Content Negotiator 使用我的自定义格式化程序。感谢您的帮助。

【问题讨论】:

    标签: asp.net-mvc-routing asp.net-web-api2 content-negotiation


    【解决方案1】:

    由于问题很老,但仍然没有答案:

    一般来说,这个链接应该会有所帮助:


    到问题中的代码:

    • 看来您需要从 BufferedMediaTypeFormatter(sync) 或 MediaTypeFormatter`(async) 扩展
    • 您需要让HttpConfiguration.Formatters (link) 知道您的格式化程序

    您可能希望在完整应用程序的配置中执行此操作。 为了进行测试,您可以添加到单个 ApiController 中,如下所示。

    未经测试的示例

    public class TestController : ApiController
    {
        TestController() {
          Configuration.Formatters.Add(new ExcelFormatter());
        }
    
        public HttpResponseMessage Get()
        {
            var items = new[] {"test1", "test2", "test3"};
            return Request.CreateResponse(HttpStatusCode.OK, items);
        }
    }
    ```
    
    
    
    

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 1970-01-01
      • 2014-12-22
      • 2018-05-08
      • 2014-07-07
      • 2013-08-14
      • 1970-01-01
      • 2016-09-13
      • 2014-11-15
      相关资源
      最近更新 更多