繁体   English   中英

执行给定动作以接受给定内容类型的属性?

[英]Attribute to make a given action to accept a given content-type?

在ASP.NET Core MVC中是否可以仅更改某些操作以接受具有属性的plain/textapplication/xml (即content-type ),而无需更改默认输入格式器?

现成的,ASP.NET Core仅支持JSON或XML。 只要设置了有效内容的内容类型,无论控制器如何操作,它都应该正确地反序列化。

如果要支持其他任何内容类型(例如,文本/纯文本),则可以创建自定义格式器

直接从aspnet样本回购中获取的示例:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM