zoukankan      html  css  js  c++  java
  • MVC WebApi 将返回值改为JSON格式

    新增一个类:

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

    修改WebApiConfig.cs 中的Register方法。

    最后一行增加:

     config.Formatters.Add(new BrowserJsonFormatter());

    修改后:

       public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
                // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
                // 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712//config.EnableQuerySupport();
    
                // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
                // 有关详细信息,请参阅: http://www.asp.net/web-api
                config.EnableSystemDiagnosticsTracing();
                config.Formatters.Add(new BrowserJsonFormatter());
            }
        }

     解决方案来自stackoverflow。

    原文出自:

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

  • 相关阅读:
    网络爬虫(抓取)正则表达式 (多线程协作)
    Asp.net 主题
    Asp.net 菜单控件
    CSS 布局Float 【4】
    CSS 布局Float 【3】
    CSS 布局Float 【2】
    CSS 布局Float 【1】
    CSS 布局Float 【0】
    Asp.Net 母版页
    Sql Server 远程过程调用失败
  • 原文地址:https://www.cnblogs.com/qiqi9039420/p/5458628.html
Copyright © 2011-2022 走看看