C# WebApi 返回JSON

原文: C# WebApi 返回JSON

在默认情况下,当我们新建一个webapi项目,会自动返回XML格式的数据,如果我们想返回JSON的数据,可以设置下面的三种方法。

1. 不用改配置文件,在Controller的方法中,直接返回HttpResponseMessage

        public HttpResponseMessage ReturnJson()
        {
            //初始化测试对象
              TestJsonObj t = new TestJsonObj();
            t.Name = "alun";
            t.Address = "GZ";

            //OBJ转化成JSON
            string json = JsonConvert.SerializeObject(t);

            //返回json数
              return new HttpResponseMessage()
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json"),
            };
        }

TestJsonObj是我们测试的类

上面的方法比较繁杂,但是灵活。每次都要把对象转换成JSON,效率上有点慢。

2. 在全局设置中,把所有返回的格式清除,设置JSON。所有的返回的xml格式都会被清除

在WebApiConfig类的Register方法中,我们添加下面代码:

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

这种方式虽然可以实现功能,但是所有的conent negotiation还是会发生,这就会产生以下额外的开销了。因为,你已经知道要返回的结果了,也只想返回Json,其他的content negotiation都不需要了。

3. 在全局设置中,使用自定义的只返回Json Result。只让api接口中替换xml,返回json

在WebApiConfig类的Register方法中,我们添加下面代码:

var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

使用自定义的只返回Json Result的content negotiation代替Web Api中默认的content negotiation。

本文推荐方法3,因为简单好用。

注意:

如果使用了swagger:

当使用方法1,在swagger页面上,返回的obj的说明文档不会显示出来

image

当使用方法3,swagger说明文档会一直处于fetching resource的状态。

image

所以我们在测试的时候使用方法2,正式环境的时候使用方法3,做一个判断就可以了,如下:

            //设置返回json
            if (CPublicAttribute.TestEnviroment)
            {
                config.Formatters.Clear();
                config.Formatters.Add(new JsonMediaTypeFormatter());
            }
            else
            {
                var jsonFormatter = new JsonMediaTypeFormatter();
                config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/10347507.html