分类:
.net后台框架
1.对于自定义的Accept需要进行注册
比如我这里的 application/vnd.cgzl.hateoas+json
services.AddMvc(option => { option.ReturnHttpNotAcceptable = true; //option.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); #region 注册请求的media type商业类型 var outputFormatter = option.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault(); if (outputFormatter != null) { outputFormatter.SupportedMediaTypes.Add("application/vnd.cgzl.hateoas+json"); } #endregion }).AddJsonOptions(options=> { //输出小写 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); });
2.写验证特性
RequestHeaderMatchingMediaTypeAttribute.cs
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)] public class RequestHeaderMatchingMediaTypeAttribute : Attribute, IActionConstraint { private readonly string _requestHeaderToMatch; private readonly string[] _mediaTypes; /// <summary> /// /// </summary> /// <param name="requestHeaderToMatch"> 请求头部的类型 </param> /// <param name="mediaTypes"> mediaTypes类型 </param> public RequestHeaderMatchingMediaTypeAttribute(string requestHeaderToMatch, string[] mediaTypes) { _requestHeaderToMatch = requestHeaderToMatch; _mediaTypes = mediaTypes; } /// <summary> /// 如果请求的Header包含该枚举类型就算通过 /// </summary> /// <param name="context"></param> /// <returns></returns> public bool Accept(ActionConstraintContext context) { var requestHeaders = context.RouteContext.HttpContext.Request.Headers; if (!requestHeaders.ContainsKey(_requestHeaderToMatch)) { return false; } foreach (var mediaType in _mediaTypes) { var mediaTypeMatches = string.Equals(requestHeaders[_requestHeaderToMatch].ToString(), mediaType, StringComparison.OrdinalIgnoreCase); if (mediaTypeMatches) { return true; } } return false; } public int Order { get; } = 0; }
Result:
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
评价
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术