电脑桌面
添加蚂蚁七词文库到电脑桌面
安装后可以在桌面快捷访问

.net webapi 返回json全局配置及使用特性路由

来源:金蝶云社区作者:金蝶2024-09-163

.net webapi 返回json全局配置及使用特性路由

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Formatting;
using System.Text;
using System.Web.Http;

namespace WebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            #region json相关配置调整

            // json格式化时,[Serializable]会导致读取到私有属性,此处取消读取私有属性
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver() { IgnoreSerializableAttribute = true };

            // 删除xml返回格式
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            // 添加json返回格式(可省略,删除XML后,默认以json格式返回)
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));

            // 忽略循环引用
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            //WebApi 返回的 JSON 结果中将 null 转换为 ""
            GlobalConfiguration.Configuration.Formatters.InsertRange(0, new List<MediaTypeFormatter> { new NullToEmptyJsonFormatter() });

            // 日期格式
            ReturnDataFormatInJsonSerializersSettings();

            #endregion

            #region 路由配置

            //使用特性路由,路由路径直观
            config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{action}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            #endregion
        }

        /// <summary>
        /// 日期序列化为 yyyy-MM-dd HH:mm:ss格式
        /// </summary>
        private static void ReturnDataFormatInJsonSerializersSettings()
        {
            var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
            settings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
            settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
        }
    }

    internal class NullToEmptyJsonFormatter : JsonMediaTypeFormatter
    {
        public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding)
        {
            if (type == nul

.net webapi 返回json全局配置及使用特性路由

using Newtonsoft.Json;using Newtonsoft.Json.Serialization;using System;using System.Collections.Generic;using System.IO;using Syst...
点击下载文档文档为doc格式

声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。如若本站内容侵犯了原著者的合法权益,可联系本站删除。

已经是第一篇
确认删除?
回到顶部
客服QQ
  • 客服QQ点击这里给我发消息
QQ群
  • 答案:my7c点击这里加入QQ群
支持邮箱
微信
  • 微信