.net webapi 返回json全局配置及使用特性路由原创
1人赞赏了该文章
1,413次浏览
编辑于2022年03月07日 19:52:40
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); } } }
赞 1
1人点赞
还没有人点赞,快来当第一个点赞的人吧!
打赏
0人打赏
还没有人打赏,快来当第一个打赏的人吧!
推荐阅读
您的鼓励与嘉奖将成为创作者们前进的动力,如果觉得本文还不错,可以给予作者创作打赏哦!
请选择打赏金币数 *
10金币20金币30金币40金币50金币60金币
可用金币: 0