如何为纯文本发布到的ASP.NET Web API端点? [英] how to post plain text to ASP.NET Web API endpoint?

查看:395
本文介绍了如何为纯文本发布到的ASP.NET Web API端点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有定义控制器动作的ASP.NET Web API端点如下:

  [HttpPost]
公众的Htt presponseMessage邮报([FromBody]对象文本)

如果我的岗位要求的身体包含纯文本(即不应该PTED为JSON,XML,或任何其他特殊格式间$ P $),那么我想我可能只是包括下面的头我的要求:

 的Content-Type:text / plain的

不过,我收到错误:

 无MediaTypeFormatter可从与媒体类型文本/纯'的内容读类型'对象'的对象。

如果我改变我的控制器操作方法签名为:

  [HttpPost]
公众的Htt presponseMessage邮报([FromBody]字符串文本)

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

 无MediaTypeFormatter可从与媒体类型text / plain的内容阅读类型的对象字符串''。


解决方案

其实这是一个耻辱,网络API不具有 MediaTypeFormatter 纯文本。下面是我实现的人。它也可以用于发布内容。

 公共类TextMediaTypeFormatter:MediaTypeFormatter
{
    公共TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(新MediaTypeHeaderValue(text / plain的));
    }    公共覆盖任务<对象> ReadFromStreamAsync(类型类型,流readStream,HttpContent内容,IFormatterLogger formatterLogger)
    {
        VAR taskCompletionSource =新TaskCompletionSource<对象>();
        尝试
        {
            VAR的MemoryStream =新的MemoryStream();
            readStream.CopyTo(MemoryStream的);
            变种S = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            taskCompletionSource.SetResult(多个);
        }
        赶上(例外五)
        {
            taskCompletionSource.SetException(E);
        }
        返回taskCompletionSource.Task;
    }    公众覆盖任务WriteToStreamAsync(类型类型,对象的值,流writeStream,HttpContent内容,System.Net.TransportContext transportContext,System.Threading.CancellationToken的CancellationToken)
    {
        变种抛光轮= System.Text.Encoding.UTF8.GetBytes(value.ToString());
        返回writeStream.WriteAsync(BUFF,0,buff.Length,的CancellationToken);
    }    公众覆盖布尔CanReadType(类型类型)
    {
        返回类型== typeof运算(字符串);
    }    公众覆盖布尔CanWriteType(类型类型)
    {
        返回类型== typeof运算(字符串);
    }
}

您需要通过类似的东西在你的HttpConfig以注册此格式:

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

I have an ASP.NET Web API endpoint with controller action defined as follows :

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

If my post request body contains plain text ( i.e. should not be interpreted as json, xml, or any other special format ), then I thought I could just include following header to my request :

Content-Type: text/plain

However, I receive error :

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

If I change my controller action method signature to :

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

I get a slightly different error message :

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

解决方案

Actually it's a shame that web API doesn't have a MediaTypeFormatter for plain text. Here is the one I implemented. It can also be used to Post content.

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);
    }
}

You need to "register" this formatter in your HttpConfig by something like that:

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

这篇关于如何为纯文本发布到的ASP.NET Web API端点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆