【问题标题】:How to Send a simple string to Web Api C#?如何向 Web Api C# 发送一个简单的字符串?
【发布时间】:2017-05-20 16:31:09
【问题描述】:

我有这个简单的动作

public void Post([FromBody] string t)
{
    var test = t;
}

我正在尝试通过邮递员使用“这是一个简单的字符串”的正文来发帖(注意我的文本会更长,所以我想通过正文而不是查询来做)。

我收到此错误

{
  "Message": "The request entity's media type 'text/plain' is not supported for this resource.",
  "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'.",
  "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
  "StackTrace": "   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}

【问题讨论】:

  • 错误消息指出“请求实体的媒体类型'text/plain'”。要么更改您的服务以接受它,要么让 Postman 以不同的媒体类型(例如 JSON)发送它。后者将是更简单的解决方案,因为看起来您正在使用标准 ASP.NET Web API,并且它们的默认值是 JSON。
  • 如果我使用 json(我通常做的),我需要正确的 json 格式。我正在尝试发送一个 csv 数据文件。
  • 您必须接受 CSV 文件。如果您正在使用 Web.API 并且需要发送文件,您最好接受 Stream,而不是 string
  • 如何接受流?你有什么例子吗?
  • 这不是你的问题 ;-) 请在互联网上搜索。那里有很多教程。这是对该主题的 SO 问题/答案和良好的示例代码:stackoverflow.com/questions/10320232/…

标签: c# asp.net-web-api postman


【解决方案1】:

错误消息指出“...请求实体的媒体类型'text/plain'”。要么更改您的服务以接受它,要么让 Postman 以不同的媒体类型(例如 JSON)发送它。后者将是更简单的解决方案,因为看起来您正在使用标准的 ASP.NET Web API,并且它们的默认值是 JSON。

发送此数据:

{ "t": "this is a simple string" }

...你会很可爱的。

【讨论】:

    【解决方案2】:

    正如@Quality Catalyst 所说,您可以更改请求内容类型并以 json 格式发送字符串。或者您可以添加 text/plain 媒体类型格式化程序:

    public class PlainTextMediaTypeFormatter : MediaTypeFormatter
    {
        public PlainTextMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
        }
    
        public override bool CanReadType(Type type)
        {
            return type == typeof(string);
        }
    
        public override bool CanWriteType(Type type)
        {
            return false; // you can return true and override WriteToStreamAsync
        }
    
        public override Task<object> ReadFromStreamAsync(Type type,
            Stream readStream, HttpContent content, IFormatterLogger formatterLogger,
            CancellationToken cancellationToken)
        {
            var memoryStream = new MemoryStream();
            readStream.CopyTo(memoryStream);
            return Task.FromResult((object)Encoding.UTF8.GetString(memoryStream.ToArray()));
        }     
    }
    

    并在 WebApiConfig 中注册此格式化程序:

    config.Formatters.Add(new PlainTextMediaTypeFormatter());
    

    之后,您将能够在请求正文中以纯文本形式发送字符串。

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 2023-03-12
      • 2020-01-18
      • 2012-12-24
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多