使用更新的ASP。NET Web API,在Chrome中我看到XML -我如何将其更改为请求JSON,以便我可以在浏览器中查看它?我相信这只是请求头的一部分,我是正确的吗?
当前回答
config.Formatters.Remove(config.Formatters.XmlFormatter);
其他回答
我不清楚为什么答案会这么复杂。当然,有很多方法可以做到这一点,QueryStrings,头和选项…但我认为最好的做法很简单。你请求一个简单的URL(例如:http://yourstartup.com/api/cars),作为回报,你得到JSON。你得到JSON和适当的响应头:
Content-Type: application/json
在寻找这个问题的答案时,我发现了这个帖子,并不得不继续下去,因为这个公认的答案并不完全正确。我确实找到了一个答案,我觉得它太简单了,不是最好的答案:
设置默认的WebAPI格式化程序
我把我的小费也加在这里。
WebApiConfig.cs
namespace com.yourstartup
{
using ...;
using System.Net.Http.Formatting;
...
config.Formatters.Clear(); //because there are defaults of XML..
config.Formatters.Add(new JsonMediaTypeFormatter());
}
我确实有一个问题,默认(至少我看到的那些)来自哪里。它们是. net默认的,还是在其他地方创建的(由我项目中的其他人创建)。无论如何,希望这能有所帮助。
在WebApiConfig.cs中,在Register函数的末尾添加:
// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);
源。
在最新版本的ASP.net WebApi 2中,在WebApiConfig.cs下,这将工作:
config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
只需在WebApiConfig类中添加这两行代码
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//add this two line
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
............................
}
}
从MSDN构建一个单页应用程序与ASP。NET和AngularJS(大约41分钟)。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ... possible routing etc.
// Setup to return json and camelcase it!
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
它应该是当前的,我试过了,它工作。
推荐文章
- 如何合并2 JSON对象从2个文件使用jq?
- 如何禁用谷歌翻译从HTML在Chrome
- 在VS Code中禁用“Comments are not allowed In JSON”错误
- 如何在Kotlin解析JSON ?
- JSON文件的蒙古导入
- Chrome开发工具:如何找出什么是覆盖CSS规则?
- 如何用jQuery / JavaScript解析JSON数据?
- jQuery在请求体中发布有效的json
- 将JSON显示为HTML
- 在JSON键名中哪些字符是有效的/无效的?
- 如何JSON序列化集?
- 如何检查JSON键是否存在?
- 返回内容与IHttpActionResult非ok响应
- 资源解释为样式表,但以MIME类型text/html传输(似乎与web服务器无关)
- Chrome iOS(和Safari)的远程调试