c# - 如何将纯文本发送到 ASP.NET Web API 端点?

标签 c# asp.net-web-api content-type

我有一个 ASP.NET Web API 端点,其 Controller 操作定义如下:

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

如果我的帖子请求正文包含纯文本(即不应解释为 json、xml 或任何其他特殊格式),那么我认为我可以在我的请求中包含以下 header :

Content-Type: text/plain

但是,我收到错误:

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

如果我将 Controller 操作方法签名更改为:

[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, 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());

关于c# - 如何将纯文本发送到 ASP.NET Web API 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25631970/

相关文章:

c# - 尝试设置 CruiseControl.net 时出现 CS0006 错误

c# - 非常规年份的 DateTime.ParseExact

c# - 如何通过 ASP.NET 中的另一个下拉列表过滤下拉列表值,c#

c# - 如何将条件必需属性放入类属性中以使用 WEB API?

c# - 从 PostAsJsonAsync 获取响应

php - 如何使用非默认内容类型调用 PHP Soap 1.1

c# - 无法将类型为 'Newtonsoft.Json.Linq.JObject' 的对象转换为类型 'System.Runtime.Serialization.ISafeSerializationData'

c# - 将 IPv6 环回地址解析为 Uri

php - 如何在cakephp中写内容类型?

http - mediatype、contenttype 和 mimetype 之间有什么区别?