如何将纯文本发布到ASP.NET Web API端点?
发布时间:2020-05-24 00:32:17 所属栏目:asp.Net 来源:互联网
导读:我有一个ASP.NET Web API端点,其控制器操作定义如下: [HttpPost]public HttpResponseMessage Post([FromBody] object text) 如果我的帖子请求正文包含纯文本(即不应该被解释为json,xml或任何其他特殊格式),那么我以为我可以在我的请求中包含以下标题: Conte
|
我有一个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()); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 窗口身份验证在MVC4中不起作用
- asp.net-mvc – 仅在MVC4 BundleConfig中缩小脚本
- asp.net-mvc – 如何根据用户过滤MVC 4中的结果
- asp.net-mvc – MVC索引页面和过滤器
- ASP.NET Membership API强制更改密码
- .net – 如何强制硬刷新(ctrl F5)?
- ASP.Net Checkbox值在回发错误?
- asp.net – 向其他人提供一个Web API转发请求的最佳方式
- asp.net-mvc – System.NotSupportedException:不支持指定
- asp.net-mvc-3 – ASP.NET MVC3项目并不总是发布所有的视图
推荐文章
站长推荐
- asp.net – 程序或函数期望未提供的参数
- asp.net – 有人有一种方法来保持页面呈现一旦一
- asp.net+js实现批量编码与解码的方法
- asp.net-mvc – 多个DbContext,多个Database.Set
- asp.net-mvc-3 – 不再使用XXXX.现在用于检测模型
- asp.net-mvc – 嵌套TagBuilder -as TagBuilderT
- 如何最小化ASP.NET C#项目DLL大小?
- asp.net-web-api – 自定义身份验证asp.net核心w
- asp.net – 如何在运行时设置ObjectDataSource选
- asp.net-mvc – 如何访问querystring在ASP.Net M
热点阅读
