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

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...