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

WebApi返回類型設置為json的三種方法

都是 eas Matter 配置 type edi types 分享 code

web api寫api接口時默認返回的是把你的對象序列化後以XML形式返回,那麽怎樣才能讓其返回為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";

WebApi返回類型設置為json的三種方法