asp.net – 为WebAPI操作设置默认的Media Formatter
发布时间:2020-12-16 07:40:50 所属栏目:asp.Net 来源:网络整理
导读:我已经实现了一个自定义媒体格式化程序,当客户端专门请求“csv”格式时它很有用. 我用这段代码测试了我的api控制器: HttpClient client = new HttpClient(); // Add the Accept header client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHe
我已经实现了一个自定义媒体格式化程序,当客户端专门请求“csv”格式时它很有用.
我用这段代码测试了我的api控制器: 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),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-mvc – 如何在ASP.NET MVC中向用户提供动
- 启用AllowSorting时,ASP.NET GridView标题行文本
- asp.net-mvc – 如何在Custom Helper中合并htmlA
- asp.net – IE10 SCRIPT5009:’__doPostBack’未
- asp.net – 在谷歌地图和谷歌地球之间切换
- asp.net-mvc – 为什么MVC提供的Default Account
- asp.net-mvc – 如何从用户友好的URL中删除不必要
- asp.net-mvc-3 – 剃刀中的部分的默认内容
- asp.net-mvc – 从一个项目到另一个项目调用控制
- asp.net-mvc-2 – 将EDMX文件移动到新项目导致:
热点阅读