使用更新的ASP。NET Web API,在Chrome中我看到XML -我如何将其更改为请求JSON,以便我可以在浏览器中查看它?我相信这只是请求头的一部分,我是正确的吗?
当前回答
返回正确的格式是由媒体类型格式化程序完成的。 正如其他人提到的,你可以在WebApiConfig类中做到这一点:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
// Configure Web API to return JSON
config.Formatters.JsonFormatter
.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
...
}
}
欲了解更多信息,请查看:
ASP中的媒体格式化器。NET Web API ASP中的内容协商。NET Web API。
如果您的操作返回XML(这是默认情况),并且您只需要一个特定的方法来返回JSON,那么您可以使用ActionFilterAttribute并将其应用于特定的操作。
过滤器属性:
public class JsonOutputAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
var value = content.Value;
Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0];
var httpResponseMsg = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
RequestMessage = actionExecutedContext.Request,
Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null)
};
actionExecutedContext.Response = httpResponseMsg;
base.OnActionExecuted(actionExecutedContext);
}
}
适用于行动:
[JsonOutput]
public IEnumerable<Person> GetPersons()
{
return _repository.AllPersons(); // the returned output will be in JSON
}
注意,您可以省略动作修饰上的Attribute这个词,只使用[JsonOutput]而不是[JsonOutputAttribute]。
其他回答
返回正确的格式是由媒体类型格式化程序完成的。 正如其他人提到的,你可以在WebApiConfig类中做到这一点:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
// Configure Web API to return JSON
config.Formatters.JsonFormatter
.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
...
}
}
欲了解更多信息,请查看:
ASP中的媒体格式化器。NET Web API ASP中的内容协商。NET Web API。
如果您的操作返回XML(这是默认情况),并且您只需要一个特定的方法来返回JSON,那么您可以使用ActionFilterAttribute并将其应用于特定的操作。
过滤器属性:
public class JsonOutputAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
var value = content.Value;
Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0];
var httpResponseMsg = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
RequestMessage = actionExecutedContext.Request,
Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null)
};
actionExecutedContext.Response = httpResponseMsg;
base.OnActionExecuted(actionExecutedContext);
}
}
适用于行动:
[JsonOutput]
public IEnumerable<Person> GetPersons()
{
return _repository.AllPersons(); // the returned output will be in JSON
}
注意,您可以省略动作修饰上的Attribute这个词,只使用[JsonOutput]而不是[JsonOutputAttribute]。
看看WebAPI中的内容协商。这些(第1部分和第2部分)非常详细和彻底的博客文章解释了它是如何工作的。
简而言之,您是对的,只需要设置Accept或Content-Type请求头。如果你的Action没有返回特定的格式,你可以设置Accept: application/json。
WebApiConfig是你可以配置你想要输出json还是xml的地方。缺省情况下为xml格式。在register函数中,我们可以使用HttpConfiguration Formatters来格式化输出。
System.Net.Http.Headers => MediaTypeHeaderValue("text/html")需要获得json格式的输出。
这里有一个类似于杰森的解决方案。ceneno 's和其他答案,但使用System.Net.Http.Formatting的内置扩展。
public static void Register(HttpConfiguration config)
{
// add support for the 'format' query param
// cref: http://blogs.msdn.com/b/hongyes/archive/2012/09/02/support-format-in-asp-net-web-api.aspx
config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
// ... additional configuration
}
在WebApi的早期版本中,该解决方案主要用于支持OData的$格式,但它也适用于非OData实现,并返回 内容类型:application / json;Charset =utf-8报头。
它允许您在使用浏览器测试时将&$format=json或&$format=xml附加到uri的末尾。在使用非浏览器客户端(可以设置自己的头文件)时,它不会干扰其他预期行为。
你只需要像这样修改App_Start/WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
//Below formatter is used for returning the Json result.
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
//Default route
config.Routes.MapHttpRoute(
name: "ApiControllerOnly",
routeTemplate: "api/{controller}"
);
}
推荐文章
- 如何合并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)的远程调试