【问题标题】:415 when passing string parameter to Web Api Post method将字符串参数传递给 Web Api Post 方法时出现 415
【发布时间】:2015-12-28 17:11:28
【问题描述】:

当我将此请求发布到 http://localhost:61679/api/Login:

Headers =>  Content-Type: text/plain
Body =>     grant_type=password&username=doug&password=12345

我收到415 Unsupported Media Type:

HTTP/1.1 415 Unsupported Media Type
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcZGV2ZWxvcG1lbnRcYml0Y29pblxwYXltZW50cy1zZXJ2aWNlLW5vLWNoZWNrc3VtLW5vLXVzZXJcUGF5bWVudHNTZXJ2aWNlXGFwaVxBdXRoZW50aWNhdGU=?=
X-Powered-By: ASP.NET
Date: Mon, 28 Dec 2015 16:58:36 GMT
Content-Length: 900

{"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.Net.Http.HttpContentExtensions.ReadAsAsync(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)"}

控制器:

    // POST api/Login
    public HttpResponseMessage Post([FromBody]string loginDetails)
    {
       // process loginDetails here
    }

【问题讨论】:

  • 只是好奇 - 为什么你会在你的控制器中接受一个字符串,但看起来你正在传递一个复杂的对象?
  • 正文中的字符串应该被引用。 Content-Type 应该是 application/json。 stackoverflow.com/a/41114909/4854931

标签: asp.net asp.net-web-api asp.net-web-api2 http-status-code-415


【解决方案1】:

你必须设置你的 Content-Type:application/json; charset=utf-8 而不是 text/plain

必须创建一个视图模型

public class LoginDetails{
public string grant_type{get;set;}
public string username{get;set;}
public string password{get;set;}
}

你的行动结果是这样的

public HttpResponseMessage Post(LoginDetails loginDetails)

在请求的时候你的身体会像

 {
    "grant_type":"...",
    "username":".....",
    "password":"....."
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多