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

栏目:云星空知识作者:金蝶来源:金蝶云社区发布:2024-09-16浏览:1

.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 == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (writeStream == null)
            {
                throw new ArgumentNullException(nameof(writeStream));
            }

            if (effectiveEncoding == null)
            {
                throw new ArgumentNullException(nameof(effectiveEncoding));
            }

            JsonWriter jsonWriter = new NullToEmptyJsonWriter(new StreamWriter(writeStream, effectiveEncoding));

            if (Indent)
            {
                jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
            }

            return jsonWriter;
        }
    }

    internal class NullToEmptyJsonWriter : JsonTextWriter
    {
        public NullToEmptyJsonWriter(TextWriter textWriter) : base(textWriter) { }
        public override void WriteNull()
        {
            WriteValue(string.Empty);
        }
    }
}
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;


namespace WebApi
{
    [RoutePrefix("api/webapi")]
    public class WebApiController : ApiController
    {
        /// <summary>
        ///  POST api/webapi/test
        /// </summary>
        /// <param name="inputJO"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("test")]
        public IHttpActionResult TestApi([FromBody]JObject inputJO)
        {
            if (inputJO == null)
            {
                return NotFound();
            }
            return Ok(inputJO);
        }
   }
}


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

using Newtonsoft.Json;using Newtonsoft.Json.Serialization;using System;using System.Collections.Generic;using System.IO;using Syst...
点击下载文档
确认删除?
回到顶部
客服QQ
  • 客服QQ点击这里给我发消息