.net webapi 全局设置

using Newtonsoft.Json.Serialization;
using Sfq.WebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sfq.WebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

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

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

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

            // 开启Token全局验证服务
            config.Filters.Add(new AuthorizeAttribute());

            // Web API 路由
            config.MapHttpAttributeRoutes();

            // 日期格式
            ReturnDataFormatInJsonSerializersSettings();

            // 配置跨域
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

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

        private static void ReturnDataFormatInJsonSerializersSettings()
        {
            var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
            settings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
            settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            // long转string
            settings.Converters.Add(new Int64ToStringConverter());
        }
    }
}

  

posted @ 2021-10-14 17:01  我要找到我的全世界  阅读(395)  评论(0编辑  收藏  举报