• WebApi返回类型设置为json的三种方法


    方法一:(改配置法) 


    找到Global.asax文件,在Application_Start()方法中添加一句:

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

    修改后:

    1 protected void Application_Start() 
    2 { 
    3     AreaRegistration.RegisterAllAreas(); 
    4     WebApiConfig.Register(GlobalConfiguration.Configuration); 
    5     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    6     RouteConfig.RegisterRoutes(RouteTable.Routes); 
    7     // 使api返回为json 
    8     GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
    9 }
    View Code

    这样返回的结果就都是json类型了,但有个不好的地方,如果返回的结果是String类型,如123,返回的json就会变成"123";


    解决的方法是自定义返回类型(返回类型为HttpResponseMessage)

    public HttpResponseMessage PostUserName(User user) 
    { 
        String userName = user.userName; 
        HttpResponseMessage result = new HttpResponseMessage { Content = new     StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") }; 
        return result; 
    }
    View Code

    方法二:(万金油法) 

    方法一中又要改配置,又要处理返回值为String类型的json,甚是麻烦,不如就不用web 
    api中的的自动序列化对象,自己序列化后再返回

    public HttpResponseMessage PostUser(User user) 
    { 
        JavaScriptSerializer serializer = new JavaScriptSerializer(); 
        string str = serializer.Serialize(user); 
        HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; 
        return result; 
    }
    View Code

    方法二是我比较推荐的方法,为了不在每个接口中都反复写那几句代码,所以就封装为一个方法这样使用就方便多了。

    public static HttpResponseMessage toJson(Object obj) 
    { 
        String str; 
        if (obj is String ||obj is Char) 
        { 
            str = obj.ToString(); 
        } 
        else 
        { 
            JavaScriptSerializer serializer = new JavaScriptSerializer(); 
            str = serializer.Serialize(obj); 
        } 
        HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; 
        return result; 
    }  
    View Code

    方法三:(最麻烦的方法) 

    方法一最简单,但杀伤力太大,所有的返回的xml格式都会被毙掉,那么方法三就可以只让api接口中毙掉xml,返回json 

    先写一个处理返回的类:

    public class JsonContentNegotiator : IContentNegotiator 
    { 
        private readonly JsonMediaTypeFormatter _jsonFormatter; 
     
        public JsonContentNegotiator(JsonMediaTypeFormatter formatter) 
        { 
            _jsonFormatter = formatter; 
        } 
     
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) 
        { 
            var result = new ContentNegotiationResult(_jsonFormatter, new  MediaTypeHeaderValue("application/json")); 
            return result; 
        } 
    }
    View Code

    找到App_Start中的WebApiConfig.cs文件,打开找到Register(HttpConfiguration config)方法 

    添加以下代码:

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

    添加后代码如下:

    public static void Register(HttpConfiguration config) 
    { 
        config.Routes.MapHttpRoute( 
            name: "DefaultApi", 
            routeTemplate: "api/{controller}/{action}/{id}", 
            defaults: new { id = RouteParameter.Optional } 
        ); 
        var jsonFormatter = new JsonMediaTypeFormatter(); 
        config.Services.Replace(typeof(IContentNegotiator), new  JsonContentNegotiator(jsonFormatter)); 
    } 
    View Code
  • 相关阅读:
    数据结构基础(21) --DFS与BFS
    数据结构基础(20) --图的存储结构
    数据结构基础(19) --堆与堆排序
    数据结构基础(18) --哈希表的设计与实现
    数据结构基础(17) --二叉查找树的设计与实现
    数据结构基础(16) --树与二叉树
    数据结构基础(15) --基数排序
    数据结构基础(14) --链式队列的设计与实现
    在centOS6.5 上安装使用pipework
    数据结构基础(13) --链式栈的设计与实现
  • 原文地址:https://www.cnblogs.com/Godlovezk/p/11636595.html
Copyright © 2020-2023  润新知