加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

如何将纯文本发布到ASP.NET Web API端点?

发布时间:2020-12-15 23:45:14 所属栏目:asp.Net 来源:网络整理
导读:我有一个ASP.NET Web API端点,其控制器操作定义如下: [HttpPost]public HttpResponseMessage Post([FromBody] object text) 如果我的帖子请求正文包含纯文本(即不应该被解释为json,xml或任何其他特殊格式),那么我以为我可以在我的请求中包含以下标题: Cont
我有一个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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读