茄子在线看片免费人成视频,午夜福利精品a在线观看,国产高清自产拍在线观看,久久综合久久狠狠综合

    <s id="ddbnn"></s>
  • <sub id="ddbnn"><ol id="ddbnn"></ol></sub>

  • <legend id="ddbnn"></legend><s id="ddbnn"></s>

    C# web api返回類型設(shè)置為json的兩種方法
    來源:易賢網(wǎng) 閱讀:3915 次 日期:2014-10-11 14:03:51
    溫馨提示:易賢網(wǎng)小編為您整理了“C# web api返回類型設(shè)置為json的兩種方法”,方便廣大網(wǎng)友查閱!

    web api寫api接口時(shí)默認(rèn)返回的是把你的對象序列化后以XML形式返回,那么怎樣才能讓其返回為json呢,下面為大家介紹幾種不錯(cuò)的方法

    web api寫api接口時(shí)默認(rèn)返回的是把你的對象序列化后以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();

    }

    這樣返回的結(jié)果就都是json類型了,但有個(gè)不好的地方,如果返回的結(jié)果是String類型,如123,返回的json就會(huì)變成"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中的的自動(dòng)序列化對象,自己序列化后再返回

    代碼如下:

    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;

    }

    方法二是我比較推薦的方法,為了不在每個(gè)接口中都反復(fù)寫那幾句代碼,所以就封裝為一個(gè)方法這樣使用就方便多了。

    代碼如下:

    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格式都會(huì)被斃掉,那么方法三就可以只讓api接口中斃掉xml,返回json

    先寫一個(gè)處理返回的類:

    代碼如下:

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

    }

    方法三如果返回的結(jié)果是String類型,如123,返回的json就會(huì)變成"123",解決方法同方法一。

    其實(shí)web api會(huì)自動(dòng)把返回的對象轉(zhuǎn)為xml和json兩種格式并存的形式,方法一與方法三是斃掉了xml的返回,而方法二是自定義返回。

    更多信息請查看IT技術(shù)專欄

    更多信息請查看網(wǎng)絡(luò)編程
    易賢網(wǎng)手機(jī)網(wǎng)站地址:C# web api返回類型設(shè)置為json的兩種方法
    由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

    2026上岸·考公考編培訓(xùn)報(bào)班

    • 報(bào)班類型
    • 姓名
    • 手機(jī)號(hào)
    • 驗(yàn)證碼
    關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
    工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
    云南網(wǎng)警備案專用圖標(biāo)
    聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
    咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
    云南網(wǎng)警報(bào)警專用圖標(biāo)