C# 属性使给定的操作接受给定的内容类型?
在ASP.NET Core MVC中,是否可以只更改某些操作,以接受带有属性的C# 属性使给定的操作接受给定的内容类型?,c#,asp.net-core,.net-core,asp.net-core-mvc,C#,Asp.net Core,.net Core,Asp.net Core Mvc,在ASP.NET Core MVC中,是否可以只更改某些操作,以接受带有属性的纯/文本或应用程序/xml(即内容类型),而不更改默认的输入格式化程序?开箱即用,ASP.NET Core只支持JSON或xml。只要您设置了有效负载的内容类型,它就应该正确地反序列化,而不考虑控制器的操作 如果您希望支持任何其他内容类型(如文本/纯文本),可以创建 直接取自aspnet样本的示例: 公共类TextPlainInputFormatter:TextInputFormatter { 公共文本PlainInp
纯/文本
或应用程序/xml
(即内容类型
),而不更改默认的输入格式化程序?开箱即用,ASP.NET Core只支持JSON或xml。只要您设置了有效负载的内容类型,它就应该正确地反序列化,而不考虑控制器的操作
如果您希望支持任何其他内容类型(如文本/纯文本),可以创建
直接取自aspnet样本的示例:
公共类TextPlainInputFormatter:TextInputFormatter
{
公共文本PlainInputFormatter()
{
支持的媒体类型。添加(“文本/普通”);
SupportedEncodings.Add(UTF8EncodingWithoutBOM);
SupportedEncodings.Add(UTF16编码LittleEndian);
}
受保护的覆盖布尔CanReadType(类型)
{
返回类型==typeof(字符串);
}
公共重写异步任务ReadRequestBodyAsync(InputFormatterContext上下文,编码)
{
字符串数据=null;
使用(var streamReader=context.ReaderFactory(context.HttpContext.Request.Body,编码))
{
data=wait streamReader.ReadToEndAsync();
}
返回InputFormatterResult.Success(数据);
}
}
public class TextPlainInputFormatter : TextInputFormatter
{
public TextPlainInputFormatter()
{
SupportedMediaTypes.Add("text/plain");
SupportedEncodings.Add(UTF8EncodingWithoutBOM);
SupportedEncodings.Add(UTF16EncodingLittleEndian);
}
protected override bool CanReadType(Type type)
{
return type == typeof(string);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
string data = null;
using (var streamReader = context.ReaderFactory(context.HttpContext.Request.Body, encoding))
{
data = await streamReader.ReadToEndAsync();
}
return InputFormatterResult.Success(data);
}
}