簡體   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