【问题标题】:Unsupported media type ASP.NET Core Web API不支持的媒体类型 ASP.NET Core Web API
【发布时间】:2017-08-19 01:27:20
【问题描述】:

在前端,我使用 Angular 从表单中收集 som 数据并将其发送到我的服务器端控制器。如下图所示,我在控制器和服务上获取数据 ($scope.newData),但是当它到达服务器时,我收到以下错误:“不支持的媒体类型”并且我的 newData 为空。

我的控制器:

// Create new salesman
  $scope.addSalesman = function (newData) {
    console.log("Controller");
    console.log($scope.newData);
    myService.addNewSalesman($scope.newData).then(function (data) {
      console.log(data);
    }, function (err) {
      console.log(err);
    });
  };

我的服务:

addNewSalesman: function (newData) {
            console.log("service");
            console.log(newData)
            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: '/api/Salesman',
                headers: { 'Content-type': 'application/json' }
            }, newData).then(function (res) {
                deferred.resolve(res.data);
            }, function (res) {
                deferred.reject(res);
            });
            return deferred.promise;
        }

我的推销员模型:

public class Salesman
    {
        public int SalesmanID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public string BirthDate { get; set; }
        public int Phone { get; set; }
        public string Adress { get; set; }
        public string City { get; set; }
        public int Postal { get; set; }
        public string Role { get; set; }
    }

我的服务器端控制器:

[Route("api/[controller]")]
public class SalesmanController : Controller
{

    private readonly DataAccess _DataAccess;

    public SalesmanController() 
    { 
        _DataAccess = new DataAccess(); 
    } 

    [HttpPost]
    public IActionResult PostSalesman([FromBody] Salesman newData)
    {
        return Ok(newData); 
    }

【问题讨论】:

  • 您能看到您的 Angular 服务发送了正确的标头并发送了 JSON 有效负载吗?
  • 如果您检查元素并在网络下检查。这是我能看到的地方。
  • 我要求您向我们展示请求有效负载 + 标头 :)
  • imgur.com/a/H0hGE 不确定你是否想看我的服务,但在这里。我对帖子没有问题,但是当我不得不删除时,必须添加标题。

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


【解决方案1】:

只需将控制器中的[FromBody] 替换为[FromForm]

【讨论】:

    【解决方案2】:

    您发送的标头错误。您正在发送Content-Type: application/json,但您必须发送Accept: application/json

    Content-Type: application/json 是服务器必须发送给客户端的内容,客户端必须发送Accept 来告诉服务器它接受哪种类型的响应。

    addNewSalesman: function (newData) {
            console.log("service");
            console.log(newData)
            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: '/api/Salesman',
                headers: { 'Accept': 'application/json' }
            }, newData).then(function (res) {
                deferred.resolve(res.data);
            }, function (res) {
                deferred.reject(res);
            });
            return deferred.promise;
        }
    

    应该这样做。另请参阅 MDN 上的“Content negotiation”。

    【讨论】:

    • 这很奇怪,因为 json 是用 mvc 开箱即用注册的,只有 xml 需要单独注册。您是否一直尝试删除标题部分? Angular 应该能够在那里放置合理的默认值
    • 这很有趣,因为现在它实际上可以在没有任何标题或完全接受的情况下工作。奇怪。
    【解决方案3】:

    这是一个 CORS 问题。

    在开发过程中,可以安全地接受来自所有来源的所有 http 请求方法。将以下内容添加到您的 startup.cs:

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
    
            //Accept All HTTP Request Methods from all origins
            app.UseCors(builder =>
                builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
    
            app.UseMvc();
        }
    

    有关 CORS 的更多详细信息,请参阅 here

    【讨论】:

    • 那么生产环境的解决方案是什么?
    • 在 prod env 中,您应该在使用 CorsPolicyBuilder 类添加 CORS 中间件时指定跨域策略。您的 CORS 策略实际上是允许进入您的 API 的来源的“白名单”。在这里阅读更多:[链接]docs.microsoft.com/en-us/aspnet/core/security/…
    【解决方案4】:

    我在接收控制器方法需要一个 [FromBody] 参数的情况下遇到这种情况,但调用服务省略了该参数。 猜测一下,期望(序列化)参数的控制器方法会期望请求内容类型(MIME)为 application/json - 但是没有参数调用 POST/PUT 的 HttpClient 不会传递这个(可能只是文本/html) - 因此我们得到 415 'Unsupported Media Type'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 2020-09-25
      • 2021-12-01
      • 2021-03-31
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多