1. 程式人生 > >WebApi返回型別設定為json的三種方法

WebApi返回型別設定為json的三種方法

方法一:(改配置法) 


找到Global.asax檔案,在Application_Start()方法中新增一句:

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

修改後:

複製程式碼

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    WebApiConfig.Register(GlobalConfiguration.Configuration); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
    // 使api返回為json 
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
} 

複製程式碼

這樣返回的結果就都是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; 
} 

複製程式碼

方法二:(萬金油法) 

方法一中又要改配置,又要處理返回值為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; 
} 

複製程式碼

方法二是我比較推薦的方法,為了不在每個介面中都反覆寫那幾句程式碼,所以就封裝為一個方法這樣使用就方便多了。

複製程式碼

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; 
}   

複製程式碼

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

方法一最簡單,但殺傷力太大,所有的返回的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; 
    } 
} 
    

複製程式碼

找到App_Start中的WebApiConfig.cs檔案,開啟找到Register(HttpConfiguration config)方法 

新增以下程式碼:

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

新增後代碼如下:

複製程式碼

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)); 
}