使给定操作接受给定内容类型的属性?

是否可以在 ASP.NET Core MVC 中仅更改某些操作以接受plain/textapplication/xml(即content-type)使用属性而不更改默认输入格式化程序?



慕姐4208626
浏览 64回答 1
1回答

慕后森

开箱即用的 ASP.NET Core 仅支持 JSON 或 XML。只要您设置了负载的内容类型,无论控制器操作如何,它都应该正确反序列化。如果你想要支持任何其他内容类型(例如文本/纯文本),你可以创建一个自定义格式化程序直接取自 aspnet 示例repo的示例:public class TextPlainInputFormatter : TextInputFormatter{&nbsp; &nbsp; public TextPlainInputFormatter()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; SupportedMediaTypes.Add("text/plain");&nbsp; &nbsp; &nbsp; &nbsp; SupportedEncodings.Add(UTF8EncodingWithoutBOM);&nbsp; &nbsp; &nbsp; &nbsp; SupportedEncodings.Add(UTF16EncodingLittleEndian);&nbsp; &nbsp; }&nbsp; &nbsp; protected override bool CanReadType(Type type)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return type == typeof(string);&nbsp; &nbsp; }&nbsp; &nbsp; public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; string data = null;&nbsp; &nbsp; &nbsp; &nbsp; using (var streamReader = context.ReaderFactory(context.HttpContext.Request.Body, encoding))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data = await streamReader.ReadToEndAsync();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return InputFormatterResult.Success(data);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP