国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 建站經驗 > 正文

C# web api返回類型設置為json的兩種方法

2019-11-02 15:54:19
字體:
來源:轉載
供稿:網友

&n

天天愛去電影網[www.aikan.tv/special/tiantianaiqudianyingwang/]
bsp;web api寫api接口時默認返回的是把你的對象序列化后以XML形式返回,那么怎樣才能讓其返回為json呢,下面為大家介紹幾種不錯的方法

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";  解決的方法是自定義返回類型(返回類型為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)); }  方法三如果返回的結果是String類型,如123,返回的json就會變成"123",解決方法同方法一。  其實web api會自動把返回的對象轉為xml和json兩種格式并存的形式,方法一與方法三是斃掉了xml的返回,而方法二是自定義返回。  
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 德江县| 鄂温| 克东县| 临高县| 莱西市| 台东县| 松滋市| 东方市| 仁布县| 达孜县| 青龙| 新兴县| 子长县| 固始县| 平潭县| 泰兴市| 中超| 黄平县| 博罗县| 乾安县| 彝良县| 武穴市| 安龙县| 陈巴尔虎旗| 阿勒泰市| 洛浦县| 庆城县| 克拉玛依市| 福鼎市| 巴彦淖尔市| 巴塘县| 阿克陶县| 武清区| 胶州市| 山阴县| 当雄县| 泸西县| 尉犁县| 桐城市| 县级市| 荥经县|