【问题标题】:415 unsupported media type error when posting to aspnetcore api from angular using $http使用 $http 从 Angular 发布到 aspnetcore api 时出现 415 不支持的媒体类型错误
【发布时间】:2017-09-23 14:21:40
【问题描述】:

在 Angular 中使用如下调用:

 function Login(email, password, callback)  
 {  
        var GetAll = new Object();  
        GetAll.email = email;   
        GetAll.password = email;  
        $http({  
            url: "http://localhost:52587/api/TokenAuth/Login",  
            dataType: 'json',  
            method: 'post',  
            data: JSON.stringify(GetAll),       
            headers: {
                      'Content-Type': 'application/json'
                      }      
         }) 
      .then(function loginSuccessCallback(response)
 {...

我已经使用 swagger 和 ajax 对此进行了测试,效果很好。我在正文中使用 json 对象设置它(设置为 raw 和 JSON (application/json))。

我编写了以下 Web API:

namespace WEBAPI.Controllers  
{   
    public class user  
    {   
        public string email { get; set; }   
        public string password { get; set; }  
    }

 [Produces("application/json")]   
 [Route("api/[controller]")]       
 public class TokenAuthController : Controller    
 {

  [HttpPost("Login")]    
  public async Task`<IActionResult>` Login([FromBody]user usr)   
{   
..................               
..................             
}      
}         
}

但我收到 [FromBody] 415 unsupported media type 和 没有 [FromBody] 获得空参数。请帮帮我
有人知道我哪里出错了吗?

【问题讨论】:

    标签: c# angularjs asp.net-mvc asp.net-web-api asp.net-core-webapi


    【解决方案1】:

    你可以尝试添加accept header

     headers: {
           'Content-Type': 'application/json',
           'Accept':  'application/json'
     }  
    

    【讨论】:

    • 我也尝试过,但我得到 415 不受支持的媒体类型。
    【解决方案2】:

    没有必要对您的数据进行 JSON.stringify,因为您真正需要的是 JSON 对象。将您的数据作为字符串肯定会给您带来 415(不支持的媒体类型)错误。 你可以这样做

    $http({  
                url: "http://localhost:52587/api/TokenAuth/Login",  
                dataType: 'json',  
                method: 'post',  
                data: GetAll,       
                headers: {
                          'Content-Type': 'application/json'
                          }      
          }) 
     .then(function loginSuccessCallback(response)
    

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 2023-03-13
      • 2023-03-08
      • 1970-01-01
      • 2016-09-05
      • 2020-01-17
      • 2017-07-05
      • 2015-08-29
      相关资源
      最近更新 更多