我有一个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());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。