我有一个 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/