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

  • 相关阅读:
    attr系列保留方法使用
    利用python的标准库hashlib 的md5()生成唯一的id
    【病因】 神经衰弱的几大病因
    群里看到的一个骗子批八字的例子
    i'll make a man out of you
    It's A Good Day To Die
    两天了。照着SVN的界面画的一个界面。
    起一卦,看看我想要的,依然这么倒霉
    倒霉倒霉真倒霉,这一卦起得和上一卦一样
    只要是倒霉,起卦就能看出来
  • 原文地址:https://www.cnblogs.com/qiqi9039420/p/5458628.html
Copyright © 2011-2022 走看看