Asp.net Web Api 返回結果格式,及在瀏覽器中的顯示

來源:互聯網
上載者:User

標籤:efault   register   gis   att   center   utf-8   rri   web api   repr   

 

using System.Collections.Generic;using System.Web.Http;using ExtJS.WebApi.Data;namespace ExtJS.WebApi.Controllers{    [RoutePrefix("api/Book")]    public class BookController : ApiController    {        [Route("Get")]        public List<BookModel> Get()        {            return BookRepository.List;        }    }}

用Firefox瀏覽器,顯示:


返回的 【Content-Type】是【application/xml】

 

ExtJS 4

    Ext.regModel(‘BookInfo‘,   {       fields: [{ name: ‘Name‘, type: ‘string‘ }]   });    var bookStore = Ext.create(‘Ext.data.JsonStore‘,    {        model: ‘BookInfo‘,        proxy: {            type: ‘ajax‘,             url: baseUrl + ‘Book/Get‘,            reader: { type: ‘json‘ }        }    });

 {            xtype: ‘combo‘,            fieldLabel: ‘書籍列表‘,            listConfig: {                loadingText: ‘正在載入書籍資訊‘,                emptyText: ‘未能找到匹配值‘            },            triggerAction: ‘all‘,            store: bookStore,            displayField: "Name",            valueField: "Name",            queryMode: ‘remote‘,            queryDelay: 300 }

 

請求成功,返回資料是XML的

無法將資料顯示在下拉框中

 

IE沒問題。請求到的資料是application/json格式的資料

但是在IE中,返回的是【application/json】

 

為解決Firefox瀏覽器,請求 asp.net webapi 的資料,得到的是xml的資料,需要這樣做:

 

 

 

    public class BrowserJsonFormatter : JsonMediaTypeFormatter    {        public BrowserJsonFormatter()        {            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));            this.SerializerSettings.Formatting = Formatting.Indented;        }        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)        {            base.SetDefaultContentHeaders(type, headers, mediaType);            headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "UTF-8" };        }    }

 

\App_Start\WebApiConfig.cs

        public static void Register(HttpConfiguration config)        {           ...                       config.Formatters.Add(new BrowserJsonFormatter());        }

再次請求api

 

 

 

 

參考:

http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome

Asp.net Web Api 返回結果格式,及在瀏覽器中的顯示

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.