如何将纯文本发布到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)

我有一个稍微不同的错误信息:

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

解决方法

实际上,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,System.Net.TransportContext transportContext,System.Threading.CancellationToken cancellationToken)
    {
        var buff = System.Text.Encoding.UTF8.GetBytes(value.ToString());
        return writeStream.WriteAsync(buff,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());

猜你在找的asp.Net相关文章