简体   繁体   中英

Attribute to make a given action to accept a given content-type?

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

Out of the box, ASP.NET Core only supports JSON or XML. As long as you set the content types of the payload, it should deserialize correctly regardless of the controller action.

If you want support for any other content type (eg text/plain) you can create a custom formatter

Example taken directly from aspnet samples repo :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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