天天看點

.Net MVC 4 Web Api 輸出Json 格式

1、Global 中增加json輸出

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));      
protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     //添加json 解析  使用方法 http://xxx/api/action?json=true
     GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
     WebApiConfig.Register(GlobalConfiguration.Configuration);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
 }      

2、Global 中删除xml解析

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();      
protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     WebApiConfig.Register(GlobalConfiguration.Configuration);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     //删除xml的解析 當傳回值是string 時 直接傳回string不是json對象
     GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
 }      

3、指定傳回格式

建立方法 需要程式集:System.Web.Extensions
 public static HttpResponseMessage ToJson(Object obj)
 {
     String str;
     if (obj is String || obj is Char)
     {
         str = obj.ToString();
     }
     else
     {
         var serializer = new JavaScriptSerializer();
         str = serializer.Serialize(obj);
     }
     var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
     return result;
 }      
public HttpResponseMessage GetString(string name)
 {
     return ToJson(name);
 }      
建立JsonContentNegotiator 類
 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;
     }
 }      
WebApiConfig中使用重寫
 public static void Register(HttpConfiguration config)
 {
     config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
     );
 
     var jsonFormatter = new JsonMediaTypeFormatter();
     config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
 
     // 取消注釋下面的代碼行可對具有 IQueryable 或 IQueryable<T> 傳回類型的操作啟用查詢支援。
     // 若要避免處理意外查詢或惡意查詢,請使用 QueryableAttribute 上的驗證設定來驗證傳入查詢。
     // 有關詳細資訊,請通路 http://go.microsoft.com/fwlink/?LinkId=279712。
     //config.EnableQuerySupport();
 
     // 若要在應用程式中禁用跟蹤,請注釋掉或删除以下代碼行
     // 有關詳細資訊,請參閱: http://www.asp.net/web-api
     config.EnableSystemDiagnosticsTracing();
 }