经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
细聊ASP.NET Core WebAPI格式化程序
来源:cnblogs  作者:yi念之间  时间:2024/2/26 15:07:33  对本文有异议

前言

     我们在使用ASP.NET Core WebApi时它支持使用指定的输入和输出格式来交换数据。输入数据靠模型绑定的机制处理,输出数据则需要用格式化的方式进行处理。ASP.NET Core框架已经内置了处理JSONXML的输入和输出方式,默认的情况我们提交JSON格式的内容,它可以自行进行模型绑定,也可以把对象类型的返回值输出成JSON格式,这都归功于内置的JSON格式化程序。本篇文章我们将通过自定义一个YAML格式的转换器开始,逐步了解它到底是如何工作的。以及通过自带的JSON格式化输入输出源码,加深对Formatter程序的了解。

自定义开始

要想先了解Formatter的工作原理,当然需要从自定义开始。因为一般自定义的时候我们一般会选用自己最简单最擅长的方式去扩展,然后逐步完善加深理解。格式化器分为两种,一种是用来处理输入数据格式的InputFormatter,另一种是用来处理返回数据格式的OutputFormatter。本篇文章示例,我们从自定义YAML格式的转换器开始。因为目前YAML格式确实比较流行,得益于它简单明了的格式,目前也有很多中间件都是用YAML格式。这里我们使用的是YamlDotNet这款组件,具体的引入信息如下所示

  1. <PackageReference Include="YamlDotNet" Version="15.1.0" />

YamlInputFormatter

首先我们来看一下自定义请求数据的格式化也就是InputFormatter,它用来处理了请求数据的格式,也就是我们在Http请求体里的数据格式如何处理,手下我们需要定义个YamlInputFormatter类,继承自TextInputFormatter抽象类

  1. public class YamlInputFormatter : TextInputFormatter
  2. {
  3. private readonly IDeserializer _deserializer;
  4. public YamlInputFormatter(DeserializerBuilder deserializerBuilder)
  5. {
  6. _deserializer = deserializerBuilder.Build();
  7. //添加与之绑定的MediaType,这里其实绑定的提交的ContentType的值
  8. //如果请求ContentType:text/yaml或ContentType:text/yml才能命中该YamlInputFormatter
  9. SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/yaml"));
  10. SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/yml"));
  11. //添加编码类型比如application/json;charset=UTF-8后面的这种charset
  12. SupportedEncodings.Add(Encoding.UTF8);
  13. SupportedEncodings.Add(Encoding.Unicode);
  14. }
  15. public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
  16. {
  17. ArgumentNullException.ThrowIfNull(context);
  18. ArgumentNullException.ThrowIfNull(encoding);
  19. //获取请求Body
  20. var readStream = context.HttpContext.Request.Body;
  21. object? model;
  22. try
  23. {
  24. TextReader textReader = new StreamReader(readStream);
  25. //获取Action参数类型
  26. var type = context.ModelType;
  27. //把yaml字符串转换成具体的对象
  28. model = _deserializer.Deserialize(textReader, type);
  29. }
  30. catch (YamlException ex)
  31. {
  32. context.ModelState.TryAddModelError(context.ModelName, ex.Message);
  33. throw new InputFormatterException("反序列化输入数据时出错\n\n", ex.InnerException!);
  34. }
  35. if (model == null && !context.TreatEmptyInputAsDefaultValue)
  36. {
  37. return InputFormatterResult.NoValue();
  38. }
  39. else
  40. {
  41. return InputFormatterResult.Success(model);
  42. }
  43. }
  44. }

这里需要注意的是配置SupportedMediaTypes,也就是添加与YamlInputFormatter绑定的MediaType,也就是我们请求时设置的Content-Type的值,这个配置是必须要的,否则没办法判断当前YamlInputFormatter与哪种Content-Type进行绑定。接下来定义完了之后如何把它接入程序使用它呢?也很简单在MvcOptions中配置即可,如下所示

  1. builder.Services.AddControllers(options => {
  2. options.InputFormatters.Add(new YamlInputFormatter(new DeserializerBuilder()));
  3. });

接下来我们定义一个简单类型和Action来演示一下,类和代码不具备任何实际意义,只是为了演示

  1. [HttpPost("AddAddress")]
  2. public Address AddAddress(Address address)
  3. {
  4. return address;
  5. }
  6. public class Address
  7. {
  8. public string City { get; set; }
  9. public string Country { get; set; }
  10. public string Phone { get; set; }
  11. public string ZipCode { get; set; }
  12. public List<string> Tags { get; set; }
  13. }

我们用Postman测试一下,提交一个yaml类型的格式,效果如下所示
这里需要注意的是我们需要在Postman中设置Content-Typetext/ymltext/yaml

YamlOutputFormatter

上面我们演示了如何定义InputFormatter它的作用是将请求的数据格式化成具体类型。无独有偶,既然请求数据格式可以定义,那么输出的数据格式同样可以定义,这里就需要用到OutputFormatter。接下来我们定义一个YamlOutputFormatter继承自TextOutputFormatter抽象类,代码如下所示

  1. public class YamlOutputFormatter : TextOutputFormatter
  2. {
  3. private readonly ISerializer _serializer;
  4. public YamlOutputFormatter(SerializerBuilder serializerBuilder)
  5. {
  6. //添加与之绑定的MediaType,这里其实绑定的提交的Accept的值
  7. //如果请求Accept:text/yaml或Accept:text/yml才能命中该YamlOutputFormatter
  8. SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/yaml"));
  9. SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/yml"));
  10. SupportedEncodings.Add(Encoding.UTF8);
  11. SupportedEncodings.Add(Encoding.Unicode);
  12. _serializer = serializerBuilder.Build();
  13. }
  14. public override bool CanWriteResult(OutputFormatterCanWriteContext context)
  15. {
  16. //什么条件可以使用yaml结果输出,至于为什么要重写CanWriteResult方法,我们在后面分析源码的时候会解释
  17. string accept = context.HttpContext.Request.Headers.Accept.ToString() ?? "";
  18. if (string.IsNullOrWhiteSpace(accept))
  19. {
  20. return false;
  21. }
  22. var parsedContentType = new MediaType(accept);
  23. for (var i = 0; i < SupportedMediaTypes.Count; i++)
  24. {
  25. var supportedMediaType = new MediaType(SupportedMediaTypes[i]);
  26. if (parsedContentType.IsSubsetOf(supportedMediaType))
  27. {
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33. public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
  34. {
  35. ArgumentNullException.ThrowIfNull(context);
  36. ArgumentNullException.ThrowIfNull(selectedEncoding);
  37. try
  38. {
  39. var httpContext = context.HttpContext;
  40. //获取输出的对象,转成成yaml字符串并输出
  41. string respContent = _serializer.Serialize(context.Object);
  42. await httpContext.Response.WriteAsync(respContent);
  43. }
  44. catch (YamlException ex)
  45. {
  46. throw new InputFormatterException("序列化输入数据时出错\n\n", ex.InnerException!);
  47. }
  48. }
  49. }

同样的这里我们也添加了SupportedMediaTypes的值,它的作用是我们请求时设置的Accept的值,这个配置也是必须要的,也就是请求的头中为Accept:text/yamlAccept:text/yml才能命中该YamlOutputFormatter。配置的时候同样也在MvcOptions中配置即可

  1. builder.Services.AddControllers(options => {
  2. options.OutputFormatters.Add(new YamlOutputFormatter(new SerializerBuilder()));
  3. });

接下来我们同样还是使用上面的代码进行演示,只是我们这里更换一下重新设置一下相关Header即可,这次我们直接提交json类型的数据,它会输出yaml格式,代码什么的完全不用变,结果如下所示
这里需要注意的请求头的设置发生了变化

小结

上面我们讲解了控制请求数据格式的TextInputFormatter和控制输出格式的TextOutputFormatter。其中InputFormatter负责给ModelBinding输送类型对象,OutputFormatter负责给ObjectResult输出值,这我们可以看到它们只能控制WebAPIController/Action的且返回ObjectResult的这种情况才生效,其它的比如MinimalApiGRPC是起不到效果的。通过上面的示例,有同学心里可能会存在疑问,上面在AddControllers方法中注册TextInputFormatterTextOutputFormatter的时候,没办法完成注入的服务,比如如果YamlInputFormatterYamlOutputFormatter构造实例的时候无法获取DI容器中的实例。确实,如果使用上面的方式我们确实没办法完成这个需求,不过我们可以通过其它方法实现,那就是去扩展MvcOptions选项,实现如下所示

  1. public class YamlMvcOptionsSetup : IConfigureOptions<MvcOptions>
  2. {
  3. private readonly ILoggerFactory _loggerFactory;
  4. public YamlMvcOptionsSetup(ILoggerFactory loggerFactory)
  5. {
  6. _loggerFactory = loggerFactory;
  7. }
  8. public void Configure(MvcOptions options)
  9. {
  10. var yamlInputLogger = _loggerFactory.CreateLogger<YamlInputFormatter>();
  11. options.InputFormatters.Add(new YamlInputFormatter(new DeserializerBuilder()));
  12. var yamlOutputLogger = _loggerFactory.CreateLogger<YamlOutputFormatter>();
  13. options.OutputFormatters.Add(new YamlOutputFormatter(new SerializerBuilder()));
  14. }
  15. }

我们定义了YamlMvcOptionsSetup去扩展MvcOptions选项,然后我们将YamlMvcOptionsSetup注册到容器即可

  1. builder.Services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, YamlMvcOptionsSetup>());

探究工作方式

上面我们演示了如何自定义InputFormatterOutputFormatter,也讲解了InputFormatter负责给ModelBinding输送类型对象,OutputFormatter负责给ObjectResult输出值。接下来我们就通过阅读其中的源码来看一下InputFormatterOutputFormatter是如何工作来影响模型绑定ObjectResult的结果。

需要注意的是!我们展示的源码是删减过的,只关注我们需要关注的地方,因为源码中涉及的内容太多,不方便观看,所以只保留我们关注的地方,还望谅解。

TextInputFormatter如何工作

上面我们看到了YamlInputFormatter是继承了TextInputFormatter抽象类,并重写了ReadRequestBodyAsync方法。接下来我们就从TextInputFormatterReadRequestBodyAsync方法来入手,我们来看一下源码定义[点击查看TextInputFormatter源码??]

  1. public abstract class TextInputFormatter : InputFormatter
  2. {
  3. public IList<Encoding> SupportedEncodings { get; } = new List<Encoding>();
  4. public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
  5. {
  6. //判断Encoding是否符合我们设置的SupportedEncodings中的值
  7. var selectedEncoding = SelectCharacterEncoding(context);
  8. if (selectedEncoding == null)
  9. {
  10. var exception = new UnsupportedContentTypeException(message);
  11. context.ModelState.AddModelError(context.ModelName, exception, context.Metadata);
  12. return InputFormatterResult.FailureAsync();
  13. }
  14. //这里调用了ReadRequestBodyAsync方法
  15. return ReadRequestBodyAsync(context, selectedEncoding);
  16. }
  17. //这就是我们在YamlInputFormatter中实现的ReadRequestBodyAsync方法
  18. public abstract Task<InputFormatterResult> ReadRequestBodyAsync(
  19. InputFormatterContext context,
  20. Encoding encoding);
  21. protected Encoding? SelectCharacterEncoding(InputFormatterContext context)
  22. {
  23. var requestContentType = context.HttpContext.Request.ContentType;
  24. //解析ContentType
  25. var requestMediaType = string.IsNullOrEmpty(requestContentType) ? default : new MediaType(requestContentType);
  26. if (requestMediaType.Charset.HasValue)
  27. {
  28. var requestEncoding = requestMediaType.Encoding;
  29. if (requestEncoding != null)
  30. {
  31. //在我们设置SupportedEncodings的查找符合ContentType中包含值的
  32. for (int i = 0; i < SupportedEncodings.Count; i++)
  33. {
  34. if (string.Equals(requestEncoding.WebName, SupportedEncodings[i].WebName, StringComparison.OrdinalIgnoreCase))
  35. {
  36. return SupportedEncodings[i];
  37. }
  38. }
  39. }
  40. return null;
  41. }
  42. return SupportedEncodings[0];
  43. }
  44. }

整体来说TextInputFormatter抽象类思路相对清晰,我们实现了ReadRequestBodyAsync抽象方法,这个抽象方法被当前类的重载方法ReadRequestBodyAsync(InputFormatterContext)方法中调用。果然熟悉设计模式之后会发现设计模式无处不在,这里就是设计模式里的模板方法模式。好了,我们继续看源码TextInputFormatter类又继承了InputFormatter抽象类,我们继续来看它的实现[点击查看InputFormatter源码??]

  1. public abstract class InputFormatter : IInputFormatter, IApiRequestFormatMetadataProvider
  2. {
  3. //这里定义了SupportedMediaTypes
  4. public MediaTypeCollection SupportedMediaTypes { get; } = new MediaTypeCollection();
  5. //根据ContentType判断当前的值是否可以满足调用当前InputFormatter
  6. public virtual bool CanRead(InputFormatterContext context)
  7. {
  8. if (SupportedMediaTypes.Count == 0)
  9. {
  10. throw new InvalidOperationException();
  11. }
  12. if (!CanReadType(context.ModelType))
  13. {
  14. return false;
  15. }
  16. //获取ContentType的值
  17. var contentType = context.HttpContext.Request.ContentType;
  18. if (string.IsNullOrEmpty(contentType))
  19. {
  20. return false;
  21. }
  22. //判断SupportedMediaTypes是否包含ContentType包含的值
  23. return IsSubsetOfAnySupportedContentType(contentType);
  24. }
  25. private bool IsSubsetOfAnySupportedContentType(string contentType)
  26. {
  27. var parsedContentType = new MediaType(contentType);
  28. //判断设置的SupportedMediaTypes是否匹配ContentType的值
  29. for (var i = 0; i < SupportedMediaTypes.Count; i++)
  30. {
  31. var supportedMediaType = new MediaType(SupportedMediaTypes[i]);
  32. if (parsedContentType.IsSubsetOf(supportedMediaType))
  33. {
  34. return true;
  35. }
  36. }
  37. return false;
  38. }
  39. protected virtual bool CanReadType(Type type)
  40. {
  41. return true;
  42. }
  43. //核心方法
  44. public virtual Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
  45. {
  46. return ReadRequestBodyAsync(context);
  47. }
  48. //抽象方法ReadRequestBodyAsync
  49. public abstract Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context);
  50. //获取当前InputFormatter支持的dContentType
  51. public virtual IReadOnlyList<string>? GetSupportedContentTypes(string contentType, Type objectType)
  52. {
  53. if (SupportedMediaTypes.Count == 0)
  54. {
  55. throw new InvalidOperationException();
  56. }
  57. if (!CanReadType(objectType))
  58. {
  59. return null;
  60. }
  61. if (contentType == null)
  62. {
  63. return SupportedMediaTypes;
  64. }
  65. else
  66. {
  67. var parsedContentType = new MediaType(contentType);
  68. List<string>? mediaTypes = null;
  69. foreach (var mediaType in SupportedMediaTypes)
  70. {
  71. var parsedMediaType = new MediaType(mediaType);
  72. if (parsedMediaType.IsSubsetOf(parsedContentType))
  73. {
  74. if (mediaTypes == null)
  75. {
  76. mediaTypes = new List<string>(SupportedMediaTypes.Count);
  77. }
  78. mediaTypes.Add(mediaType);
  79. }
  80. }
  81. return mediaTypes;
  82. }
  83. }
  84. }

这个类比较核心,我们来解析一下里面设计到的相关逻辑

  • 先来看ReadAsync方法,这是被调用的根入口方法,这个方法调用了ReadRequestBodyAsync抽象方法,这也是模板方法模式ReadRequestBodyAsync方法正是TextInputFormatter类中被实现的。
  • CanRead方法的功能是根据请求头里的Content-Type是否可以命中当前InputFormatter子类,所以它是决定我们上面YamlInputFormatter方法的校验方法。
  • GetSupportedContentTypes方法则是在Content-Type里解析出符合SupportedMediaTypes设置的MediaType。因为在Http的Header里,每一个键是可以设置多个值的,用;分割即可。

上面我们看到了InputFormatter类实现了IInputFormatter接口,看一下它的定义

  1. public interface IInputFormatter
  2. {
  3. bool CanRead(InputFormatterContext context);
  4. Task<InputFormatterResult> ReadAsync(InputFormatterContext context);
  5. }

通过IInputFormatter接口的定义我们流看到了,它只包含两个方法CanReadReadAsync。其中CanRead方法用来校验当前请求是否满足命中IInputFormatter实现类,ReadAsync方法来执行具体的策略完成请求数据到具体类型的转换。接下来我们看一下重头戏,在模型绑定中是如何调用IInputFormatter接口集合的

  1. public class BodyModelBinderProvider : IModelBinderProvider
  2. {
  3. private readonly IList<IInputFormatter> _formatters;
  4. private readonly MvcOptions? _options;
  5. public IModelBinder? GetBinder(ModelBinderProviderContext context)
  6. {
  7. ArgumentNullException.ThrowIfNull(context);
  8. //判断当前Action参数是否可以满足当前模型绑定类
  9. if (context.BindingInfo.BindingSource != null &&
  10. context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Body))
  11. {
  12. if (_formatters.Count == 0)
  13. {
  14. throw new InvalidOperationException();
  15. }
  16. var treatEmptyInputAsDefaultValue = CalculateAllowEmptyBody(context.BindingInfo.EmptyBodyBehavior, _options);
  17. return new BodyModelBinder(_formatters, _readerFactory, _loggerFactory, _options)
  18. {
  19. AllowEmptyBody = treatEmptyInputAsDefaultValue,
  20. };
  21. }
  22. return null;
  23. }
  24. }

通过BodyModelBinderProvider类我们可以看到,我们设置的IInputFormatter接口的实现类只能满足绑定Body的场景,包含我们上面示例中演示的示例和[FromBody]这种形式。接下来我们来看BodyModelBinder类中的实现[点击查看BodyModelBinder源码??]

  1. public partial class BodyModelBinder : IModelBinder
  2. {
  3. private readonly IList<IInputFormatter> _formatters;
  4. private readonly Func<Stream, Encoding, TextReader> _readerFactory;
  5. private readonly MvcOptions? _options;
  6. public BodyModelBinder(
  7. IList<IInputFormatter> formatters,
  8. IHttpRequestStreamReaderFactory readerFactory,
  9. MvcOptions? options)
  10. {
  11. _formatters = formatters;
  12. _readerFactory = readerFactory.CreateReader;
  13. _options = options;
  14. }
  15. internal bool AllowEmptyBody { get; set; }
  16. public async Task BindModelAsync(ModelBindingContext bindingContext)
  17. {
  18. //获取Action绑定参数名称
  19. string modelBindingKey;
  20. if (bindingContext.IsTopLevelObject)
  21. {
  22. modelBindingKey = bindingContext.BinderModelName ?? string.Empty;
  23. }
  24. else
  25. {
  26. modelBindingKey = bindingContext.ModelName;
  27. }
  28. var httpContext = bindingContext.HttpContext;
  29. //组装InputFormatterContext
  30. var formatterContext = new InputFormatterContext(
  31. httpContext,
  32. modelBindingKey,
  33. bindingContext.ModelState,
  34. bindingContext.ModelMetadata,
  35. _readerFactory,
  36. AllowEmptyBody);
  37. var formatter = (IInputFormatter?)null;
  38. for (var i = 0; i < _formatters.Count; i++)
  39. {
  40. //通过IInputFormatter的CanRead方法来筛选IInputFormatter实例
  41. if (_formatters[i].CanRead(formatterContext))
  42. {
  43. formatter = _formatters[i];
  44. break;
  45. }
  46. }
  47. try
  48. {
  49. //调用IInputFormatter的ReadAsync方法,把请求的内容格式转换成实际的模型对象
  50. var result = await formatter.ReadAsync(formatterContext);
  51. if (result.IsModelSet)
  52. {
  53. //将结果绑定到Action的相关参数上
  54. var model = result.Model;
  55. bindingContext.Result = ModelBindingResult.Success(model);
  56. }
  57. }
  58. catch (Exception exception) when (exception is InputFormatterException || ShouldHandleException(formatter))
  59. {
  60. }
  61. }
  62. }

通过阅读上面的源码,相信大家已经可以明白了我们定义的YamlInputFormatter是如何工作起来的。YamlInputFormatter本质是IInputFormatter实例。模型绑定类中BodyModelBinder调用了ReadAsync方法本质是调用到了ReadRequestBodyAsync方法。在这个方法里我们实现了请求yml格式到具体类型对象的转换,然后把转换后的对象绑定到了Action的参数上。

TextOutputFormatter如何工作

上面我们讲解了输入的格式化转换程序,知道了ModelBinding通过获取IInputFormatter实例来完成请求数据格式到对象的转换。接下来我们来看一下控制输出格式的OutputFormatter是如何工作的。通过上面自定义的YamlOutputFormatter我们可以看到它是继承自TextOutputFormatter抽象类。整体来说它的这个判断逻辑之类的和TextInputFormatter思路整体类似,所以咱们呢大致看一下关于工作过程的源码即可还是从WriteResponseBodyAsync方法入手[点击查看TextOutputFormatter源码??]

  1. public abstract class TextOutputFormatter : OutputFormatter
  2. {
  3. public override Task WriteAsync(OutputFormatterWriteContext context)
  4. {
  5. //获取ContentType,需要注意的是这里并非请求中设置的Content-Type的值,而是程序设置响应头中的Content-Type值
  6. var selectedMediaType = context.ContentType;
  7. if (!selectedMediaType.HasValue)
  8. {
  9. if (SupportedEncodings.Count > 0)
  10. {
  11. selectedMediaType = new StringSegment(SupportedMediaTypes[0]);
  12. }
  13. else
  14. {
  15. throw new InvalidOperationException();
  16. }
  17. }
  18. //获取AcceptCharset的值
  19. var selectedEncoding = SelectCharacterEncoding(context);
  20. if (selectedEncoding != null)
  21. {
  22. var mediaTypeWithCharset = GetMediaTypeWithCharset(selectedMediaType.Value!, selectedEncoding);
  23. selectedMediaType = new StringSegment(mediaTypeWithCharset);
  24. }
  25. else
  26. {
  27. //省略部分代码
  28. return Task.CompletedTask;
  29. }
  30. context.ContentType = selectedMediaType;
  31. //写输出头
  32. WriteResponseHeaders(context);
  33. return WriteResponseBodyAsync(context, selectedEncoding);
  34. }
  35. public abstract Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding);
  36. }

需要注意的是我们省略了很多源码,只关注我们关注的地方。这里没啥可说的和上面TextInputFormatter思路整体类似,也是基于模板方法模式入口方法其实是WriteAsync方法。不过这里需要注意的是在WriteAsync方法中ContentType,这里的ContentType并非我们在请求时设置的值,而是我们给响应头中设置值。TextOutputFormatter继承自OutputFormatter接下来我们继续看一下它的实现[点击查看OutputFormatter源码??]

  1. public abstract class OutputFormatter : IOutputFormatter, IApiResponseTypeMetadataProvider
  2. {
  3. protected virtual bool CanWriteType(Type? type)
  4. {
  5. return true;
  6. }
  7. //判断当前请求是否满足调用当前OutputFormatter实例
  8. public virtual bool CanWriteResult(OutputFormatterCanWriteContext context)
  9. {
  10. if (SupportedMediaTypes.Count == 0)
  11. {
  12. throw new InvalidOperationException();
  13. }
  14. //当前Action参数类型是否满足设定
  15. if (!CanWriteType(context.ObjectType))
  16. {
  17. return false;
  18. }
  19. //这里的ContentType依然是设置的响应头而非请求头
  20. if (!context.ContentType.HasValue)
  21. {
  22. context.ContentType = new StringSegment(SupportedMediaTypes[0]);
  23. return true;
  24. }
  25. else
  26. {
  27. //根据设置的输出头的ContentType判断是否满足自定义时设置的SupportedMediaTypes类型
  28. //比如YamlOutputFormatter中设置的SupportedMediaTypes和设置的响应ContentType是否满足匹配关系
  29. var parsedContentType = new MediaType(context.ContentType);
  30. for (var i = 0; i < SupportedMediaTypes.Count; i++)
  31. {
  32. var supportedMediaType = new MediaType(SupportedMediaTypes[i]);
  33. if (supportedMediaType.HasWildcard)
  34. {
  35. if (context.ContentTypeIsServerDefined
  36. && parsedContentType.IsSubsetOf(supportedMediaType))
  37. {
  38. return true;
  39. }
  40. }
  41. else
  42. {
  43. if (supportedMediaType.IsSubsetOf(parsedContentType))
  44. {
  45. context.ContentType = new StringSegment(SupportedMediaTypes[i]);
  46. return true;
  47. }
  48. }
  49. }
  50. }
  51. return false;
  52. }
  53. //WriteAsync虚方法也就是TextOutputFormatter中从写的方法
  54. public virtual Task WriteAsync(OutputFormatterWriteContext context)
  55. {
  56. WriteResponseHeaders(context);
  57. return WriteResponseBodyAsync(context);
  58. }
  59. public virtual void WriteResponseHeaders(OutputFormatterWriteContext context)
  60. {
  61. //这里可以看出写入的是输出的ContentType
  62. var response = context.HttpContext.Response;
  63. response.ContentType = context.ContentType.Value ?? string.Empty;
  64. }
  65. }

这里我们只关注两个核心方法CanWriteResultWriteAsync方法,其中CanWriteResult方法判断当前输出是否满足定义的OutputFormatter中设定的媒体类型,比如YamlOutputFormatter中设置的SupportedMediaTypes和设置的响应ContentType是否满足匹配关系,如果显示的指明了输出头是否满足text/yamltext/yml才能执行YamlOutputFormatter中的WriteResponseBodyAsync方法。一旦满足CanWriteResult方法则会去调用WriteAsync方法。我们可以看到OutputFormatter类实现了IOutputFormatter接口,它的定义如下所示

  1. public interface IOutputFormatter
  2. {
  3. bool CanWriteResult(OutputFormatterCanWriteContext context);
  4. Task WriteAsync(OutputFormatterWriteContext context);
  5. }

一目了然,IOutputFormatter接口暴露了CanWriteResultWriteAsync两个能力。咱们上面已经解释了这两个方法的用途,在这里就不再赘述了。我们知道使用IOutputFormatter的地方,在ObjectResultExecutor类中,ObjectResultExecutor类则是在ObjectResult类中被调用,我们看一下ObjectResult调用ObjectResultExecutor的地方

  1. public class ObjectResult : ActionResult, IStatusCodeActionResult
  2. {
  3. public override Task ExecuteResultAsync(ActionContext context)
  4. {
  5. var executor = context.HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<ObjectResult>>();
  6. return executor.ExecuteAsync(context, this);
  7. }
  8. }

上面代码中获取的IActionResultExecutor<ObjectResult>实例正是ObjectResultExecutor实例,这个可以在MvcCoreServiceCollectionExtensions类中可以看到[点击查看MvcCoreServiceCollectionExtensions源码??]

  1. services.TryAddSingleton<IActionResultExecutor<ObjectResult>, ObjectResultExecutor>();

好了,回到整体,我们看一下ObjectResultExecutor的定义[点击查看ObjectResultExecutor源码??]

  1. public partial class ObjectResultExecutor : IActionResultExecutor<ObjectResult>
  2. {
  3. public ObjectResultExecutor(OutputFormatterSelector formatterSelector)
  4. {
  5. FormatterSelector = formatterSelector;
  6. }
  7. //ObjectResult方法中调用的是该方法
  8. public virtual Task ExecuteAsync(ActionContext context, ObjectResult result)
  9. {
  10. var objectType = result.DeclaredType;
  11. //获取返回对象类型
  12. if (objectType == null || objectType == typeof(object))
  13. {
  14. objectType = result.Value?.GetType();
  15. }
  16. var value = result.Value;
  17. return ExecuteAsyncCore(context, result, objectType, value);
  18. }
  19. private Task ExecuteAsyncCore(ActionContext context, ObjectResult result, Type? objectType, object? value)
  20. {
  21. //组装OutputFormatterWriteContext,objectType为当前返回对象类型,value为返回对象的值
  22. var formatterContext = new OutputFormatterWriteContext(
  23. context.HttpContext,
  24. WriterFactory,
  25. objectType,
  26. value);
  27. //获取符合当前请求输出处理程序IOutputFormatter,并传递了ObjectResult的ContentTypes值
  28. var selectedFormatter = FormatterSelector.SelectFormatter(
  29. formatterContext,
  30. (IList<IOutputFormatter>)result.Formatters ?? Array.Empty<IOutputFormatter>(),
  31. result.ContentTypes);
  32. //省略部分代码
  33. //调用IOutputFormatter的WriteAsync的方法
  34. return selectedFormatter.WriteAsync(formatterContext);
  35. }
  36. }

上面的代码我们可以看到在ObjectResultExecutor类中,通过OutputFormatterSelectorSelectFormatter方法来选择使用哪个IOutputFormatter实例,需要注意的是调用SelectFormatter方法的时候传递的ContentTypes值是来自ObjectResult对象的ContentTypes属性,也就是我们在设置ObjectResult对象的时候可以传递的输出的Content-Type值。选择完成之后在调用具体实例的WriteAsync方法。我们来看一下OutputFormatterSelector实现类的SelectFormatter方法如何实现的,在OutputFormatterSelector的默认实现类DefaultOutputFormatterSelector中[点击查看DefaultOutputFormatterSelector源码??]

  1. public partial class DefaultOutputFormatterSelector : OutputFormatterSelector
  2. {
  3. public override IOutputFormatter? SelectFormatter(OutputFormatterCanWriteContext context, IList<IOutputFormatter> formatters, MediaTypeCollection contentTypes)
  4. {
  5. //省略部分代码
  6. var request = context.HttpContext.Request;
  7. //获取请求头Accept的值
  8. var acceptableMediaTypes = GetAcceptableMediaTypes(request);
  9. var selectFormatterWithoutRegardingAcceptHeader = false;
  10. IOutputFormatter? selectedFormatter = null;
  11. if (acceptableMediaTypes.Count == 0)
  12. {
  13. //如果请求头Accept没设置值
  14. selectFormatterWithoutRegardingAcceptHeader = true;
  15. }
  16. else
  17. {
  18. if (contentTypes.Count == 0)
  19. {
  20. //如果ObjectResult没设置ContentTypes则走这个逻辑
  21. selectedFormatter = SelectFormatterUsingSortedAcceptHeaders(
  22. context,
  23. formatters,
  24. acceptableMediaTypes);
  25. }
  26. else
  27. {
  28. //如果ObjectResult设置了ContentTypes则走这个逻辑
  29. selectedFormatter = SelectFormatterUsingSortedAcceptHeadersAndContentTypes(
  30. context,
  31. formatters,
  32. acceptableMediaTypes,
  33. contentTypes);
  34. }
  35. //如果通过ObjectResult的ContentTypes没选择出来IOutputFormatter这设置该值
  36. if (selectedFormatter == null)
  37. {
  38. if (!_returnHttpNotAcceptable)
  39. {
  40. selectFormatterWithoutRegardingAcceptHeader = true;
  41. }
  42. }
  43. }
  44. if (selectFormatterWithoutRegardingAcceptHeader)
  45. {
  46. if (contentTypes.Count == 0)
  47. {
  48. selectedFormatter = SelectFormatterNotUsingContentType(context, formatters);
  49. }
  50. else
  51. {
  52. selectedFormatter = SelectFormatterUsingAnyAcceptableContentType(context, formatters, contentTypes);
  53. }
  54. }
  55. return selectedFormatter;
  56. }
  57. private List<MediaTypeSegmentWithQuality> GetAcceptableMediaTypes(HttpRequest request)
  58. {
  59. var result = new List<MediaTypeSegmentWithQuality>();
  60. //获取请求头里的Accept的值,因为Accept的值可能有多个,也就是用;分割的情况
  61. AcceptHeaderParser.ParseAcceptHeader(request.Headers.Accept, result);
  62. for (var i = 0; i < result.Count; i++)
  63. {
  64. var mediaType = new MediaType(result[i].MediaType);
  65. if (!_respectBrowserAcceptHeader && mediaType.MatchesAllSubTypes && mediaType.MatchesAllTypes)
  66. {
  67. result.Clear();
  68. return result;
  69. }
  70. }
  71. result.Sort(_sortFunction);
  72. return result;
  73. }
  74. }

上面的SelectFormatter方法就是通过各种条件判断来选择符合要求的IOutputFormatter实例,这里依次出现了几个方法,用来可以根据不同条件选择IOutputFormatter,接下来我们根据出现的顺序来解释一下这几个方法的逻辑,首先是SelectFormatterUsingSortedAcceptHeaders方法

  1. private static IOutputFormatter? SelectFormatterUsingSortedAcceptHeaders(
  2. OutputFormatterCanWriteContext formatterContext,
  3. IList<IOutputFormatter> formatters,
  4. IList<MediaTypeSegmentWithQuality> sortedAcceptHeaders)
  5. {
  6. for (var i = 0; i < sortedAcceptHeaders.Count; i++)
  7. {
  8. var mediaType = sortedAcceptHeaders[i];
  9. //把Request的Accept值设置给Response的ContentT-ype
  10. formatterContext.ContentType = mediaType.MediaType;
  11. formatterContext.ContentTypeIsServerDefined = false;
  12. for (var j = 0; j < formatters.Count; j++)
  13. {
  14. var formatter = formatters[j];
  15. if (formatter.CanWriteResult(formatterContext))
  16. {
  17. return formatter;
  18. }
  19. }
  20. }
  21. return null;
  22. }

这个方法是通过请求头的Accept值来选择满足条件的IOutputFormatter实例。还记得上面的OutputFormatter类中的CanWriteResult方法吗就是根据ContentType判断是否符合条件,使用的就是这里的Request的Accept值。第二个出现的选择方法则是SelectFormatterUsingSortedAcceptHeadersAndContentTypes方法

  1. private static IOutputFormatter? SelectFormatterUsingSortedAcceptHeadersAndContentTypes(
  2. OutputFormatterCanWriteContext formatterContext,
  3. IList<IOutputFormatter> formatters,
  4. IList<MediaTypeSegmentWithQuality> sortedAcceptableContentTypes,
  5. MediaTypeCollection possibleOutputContentTypes)
  6. {
  7. for (var i = 0; i < sortedAcceptableContentTypes.Count; i++)
  8. {
  9. var acceptableContentType = new MediaType(sortedAcceptableContentTypes[i].MediaType);
  10. for (var j = 0; j < possibleOutputContentTypes.Count; j++)
  11. {
  12. var candidateContentType = new MediaType(possibleOutputContentTypes[j]);
  13. if (candidateContentType.IsSubsetOf(acceptableContentType))
  14. {
  15. for (var k = 0; k < formatters.Count; k++)
  16. {
  17. var formatter = formatters[k];
  18. formatterContext.ContentType = new StringSegment(possibleOutputContentTypes[j]);
  19. formatterContext.ContentTypeIsServerDefined = true;
  20. if (formatter.CanWriteResult(formatterContext))
  21. {
  22. return formatter;
  23. }
  24. }
  25. }
  26. }
  27. }
  28. return null;
  29. }

这个方法是通过ObjectResult设置了ContentTypes去匹配选择满足条件请求头的Accept值来选择IOutputFormatter实例。第三个出现的则是SelectFormatterNotUsingContentType方法

  1. private IOutputFormatter? SelectFormatterNotUsingContentType(
  2. OutputFormatterCanWriteContext formatterContext,
  3. IList<IOutputFormatter> formatters)
  4. {
  5. foreach (var formatter in formatters)
  6. {
  7. formatterContext.ContentType = new StringSegment();
  8. formatterContext.ContentTypeIsServerDefined = false;
  9. if (formatter.CanWriteResult(formatterContext))
  10. {
  11. return formatter;
  12. }
  13. }
  14. return null;
  15. }

这个方法是选择第一个满足条件的IOutputFormatter实例。还记得上面定义YamlOutputFormatter类的时候重写了CanWriteResult方法吗?就是为了杜绝被默认选中的情况,重写了CanWriteResult方法,里面添加了验证逻辑就不会被默认选中。

  1. private static IOutputFormatter? SelectFormatterUsingAnyAcceptableContentType(
  2. OutputFormatterCanWriteContext formatterContext,
  3. IList<IOutputFormatter> formatters,
  4. MediaTypeCollection acceptableContentTypes)
  5. {
  6. foreach (var formatter in formatters)
  7. {
  8. foreach (var contentType in acceptableContentTypes)
  9. {
  10. formatterContext.ContentType = new StringSegment(contentType);
  11. formatterContext.ContentTypeIsServerDefined = true;
  12. if (formatter.CanWriteResult(formatterContext))
  13. {
  14. return formatter;
  15. }
  16. }
  17. }
  18. return null;
  19. }

这个方法说的比较简单,就是通过ObjectResult设置了ContentTypes去匹配选择满足条件的IOutputFormatter实例。

到这里相信大家对关于TextOutputFormatter是如何工作的有了大致的了解,本质就是在ObjectResultExecutor类中选择合适的满足条件的IOutputFormatter实例。我们在Action中返回POCO对象、ActionResult<Type>OkObjectResult等本质都是返回的ObjectResult类型。

小结

相信通过这一小节对TextInputFormatterTextOutputFormatter源码的分析,和它们是如何工作的进行了大致的讲解。其实如果理解了源码,总结起来也很简单

  • 模型绑定类中BodyModelBinder调用了InputFormatter实例来进行对指定请求的内容进行格式转换,绑定到模型参数上的,
  • ObjectResult类的执行类ObjectResultExecutor类中通过调用满足条件OutputFormatter实例,来决定把模型输出成那种类型的数据格式,但是需要注意重写CanWriteResult方法防止被作为默认程序输出。

控制了模型绑定和输出对象转换,我们也就可以直接控制请求数据和输出数据的格式控制了。当然想更好的了解更多的细节,解惑心中疑问,还是得阅读和调试具体的源码。

相关资料

由于文章中涉及到的源码都是关于格式化程序工作过程中涉及到的源码,其它的相关源码和地址我们并没有展示出来,这里我将罗列一下对该功能理解有帮助的相关地址,方便大家阅读

总结

    本篇文章我们通过演示示例和讲解源码的方式了解了ASP.NET Core WebAPI中的格式化程序,知道结构的话了解它其实并不难,只是其中的细节比较多,需要慢慢梳理。涉及到的源码比较多,可以把本文当做一个简单的教程来看。写文章既是把自己对事物的看法分享出来,也是把自己的感悟记录下来方便翻阅。我个人很喜欢阅读源码,通过开始阅读源码感觉自己的水平有了很大的提升,阅读源码与其说是一个行为不如说是一种意识。明显的好处,一个是为了让自己对这些理解更透彻,阅读过程中可以引发很多的思考。二是通过源码可以解决很多实际的问题,毕竟大家都这么说源码之下无秘密。

??欢迎扫码关注我的公众号??

原文链接:https://www.cnblogs.com/wucy/p/18025196/aspnetcore_webapi_formatter

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号