ASP.NET Web API エンドポイントにプレーンテキストを投稿する方法は? 質問する

ASP.NET Web API エンドポイントにプレーンテキストを投稿する方法は? 質問する

次のように定義されたコントローラー アクションを持つ ASP.NET Web API エンドポイントがあります。

[HttpPost]
public HttpResponseMessage Post([FromBody] object text)

私の投稿リクエスト本文にプレーンテキストが含まれている場合(つまり、json、xml、またはその他の特別な形式として解釈されるべきではない場合)、リクエストに次のヘッダーを含めることができると考えました。

Content-Type: text/plain

しかし、次のエラーが発生します:

No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'text/plain'.

コントローラーのアクションメソッドのシグネチャを次のように変更します。

[HttpPost]
public HttpResponseMessage Post([FromBody] string text)

少し異なるエラーメッセージが表示されます:

メディア タイプが「text/plain」のコンテンツからタイプが「String」のオブジェクトを読み取るために使用できる MediaTypeFormatter がありません。

ベストアンサー1

実際のところ、Web API にプレーンテキスト用の がないのは残念ですMediaTypeFormatter。これが私が実装したものです。コンテンツを投稿するためにも使用できます。

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var taskCompletionSource = new TaskCompletionSource<object>();
        try
        {
            var memoryStream = new MemoryStream();
            readStream.CopyTo(memoryStream);
            var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            taskCompletionSource.SetResult(s);
        }
        catch (Exception e)
        {
            taskCompletionSource.SetException(e);
        }
        return taskCompletionSource.Task;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, System.Net.TransportContext transportContext, System.Threading.CancellationToken cancellationToken)
    {
        var buff = System.Text.Encoding.UTF8.GetBytes(value.ToString());
        return writeStream.WriteAsync(buff, 0, buff.Length, cancellationToken);
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return type == typeof(string);
    }
}

次のようにして、このフォーマッタを HttpConfig に「登録」する必要があります。

config.Formatters.Insert(0, new TextMediaTypeFormatter());

おすすめ記事