【发布时间】: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