Skip to content
欢迎扫码关注公众号

WebAPI 中返回 JSON 的正确做法


原文:Web Api 中返回 JSON 的正确做法
英文原文:Supporting only JSON in ASP.NET Web API – the right way


WebApiConfig.cs

cs
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());

默认情况下的返回值

js
["value1","value2"]
"1"
{"ProductID":"003","ProductName":"旺仔牛奶","ProductCategory":"食品类","TestGuid":"00000000-0000-0000-0000-000000000000"}

返回的类型分别是

cs
IEnumerable<string>
string
Product

Action返回值的自动序列化是由GlobalConfiguration控制的,可以在Application_Start中进行设置.


原文:ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml)l


cs
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();  
//默认返回 json  
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));  
//返回格式选择 datatype 可以替换为任何参数   
config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "xml", "application/xml"));

需要返回xml格式时的请求方式 http://localhost:80/api/xxx/xxxx?datatype=xml


原文:修改 mvc webapi 默认返回 json 格式


Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.