我已经实现了一个自定义媒体格式化程序,当客户端特别请求“csv”格式时,它工作得很好。
我已经使用以下代码测试了我的 api Controller :
HttpClient client = new HttpClient();
// Add the Accept header
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));
但是,当我从 Web 浏览器打开相同的 URL 时,它返回 JSON 而不是 CSV。这可能是由于标准 ASP.NET WebAPI 配置将 JSON 设置为默认媒体格式化程序,除非调用方另有指定。我希望在我拥有的所有其他 Web 服务上都有这种默认行为,但不是在返回 CSV 的单个操作上。我希望默认媒体处理程序是我实现的 CSV 处理程序。如何配置 Controller 的端点,使其默认返回 CSV 并且仅在客户端请求时返回 JSON/XML?
最佳答案
您使用的是哪个版本的 Web API?
如果您正在使用 5.0
版本,您可以使用新的 IHttpActionResult
基于逻辑如下:
public IHttpActionResult Get()
{
MyData someData = new MyData();
// creating a new list here as I would like CSVFormatter to come first. This way the DefaultContentNegotiator
// will behave as before where it can consider CSVFormatter to be the default one.
List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
respFormatters.Add(new MyCsvFormatter());
respFormatters.AddRange(Configuration.Formatters);
return new NegotiatedContentResult<MyData>(HttpStatusCode.OK, someData,
Configuration.Services.GetContentNegotiator(), Request, respFormatters);
}
如果您正在使用
4.0
版本的 Web API,那么您可以执行以下操作:public HttpResponseMessage Get()
{
MyData someData = new MyData();
HttpResponseMessage response = new HttpResponseMessage();
List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
respFormatters.Add(new MyCsvFormatter());
respFormatters.AddRange(Configuration.Formatters);
IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
ContentNegotiationResult negotiationResult = negotiator.Negotiate(typeof(MyData), Request, respFormatters);
if (negotiationResult.Formatter == null)
{
response.StatusCode = HttpStatusCode.NotAcceptable;
return response;
}
response.Content = new ObjectContent<MyData>(someData, negotiationResult.Formatter, negotiationResult.MediaType);
return response;
}
关于asp.net - 为 Web API 操作设置默认媒体格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687815/