.net core 通过不同Accept访问同方法请求不同方法处理
电脑版发表于:2019/10/30 16:04
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: