【问题标题】:ASP.NET Core POST to MVCASP.NET Core POST 到 MVC
【发布时间】:2017-03-04 19:15:35
【问题描述】:

我正在尝试从客户端向我的 ASP.NET Core 应用程序中的 MVC 控制器发出一个简单的 POST 请求。问题是,即使我已经正确设置了 ajax 调用(我认为),有效负载总是以表单 url 编码的形式提交,并且我在服务器上的模型最终为空。这是我的设置:

控制器动作定义:

[HttpPost]
public async Task<EmailResponse> SendEmail([FromBody] EmailModel model)
{
EmailResponse response = new EmailResponse();

...

return response;
}

型号:

public class EmailModel
{
[JsonProperty("fistName")]
public string FirstName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("company")]
public string Company { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}

客户端ajax调用:

$.ajax({
  type: "POST",
  url: "/Home/SendEmail",
  contentType: 'application/json; charset=utf-8',
  data: model
}).done(function (result) {
   ...
}).error(function(error) {
   ...
});

这是我的要求:

POST /Home/SendEmail HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Content-Length: 77
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
Origin: http://localhost:5000
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://localhost:5000/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: _ga=GA1.1.116706601.1460641478

firstName=Joe&lastName=Doe&email=test%40test.com&company=Acme%2C+Inc&message=

请注意请求结束时的有效负载。即使我传递一个普通的 JS 对象并将 contentType 指定为 application/json,它也不是 JSON 格式。我猜这就是为什么我的模型在服务器上总是为空的原因。

我已经盯着这个看了几个小时,看不出问题出在哪里。非常感谢任何输入。

谢谢。

【问题讨论】:

    标签: asp.net-core-mvc


    【解决方案1】:

    您的模型未序列化为 json。该对象被序列化为默认媒体类型 - 键值对 - 即所谓的“application/x-www-form-encoded”。

    尝试强制执行 JSON

    $.ajax({
      type: "POST",
      url: "/Home/SendEmail",
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(model) //notice the JSON.stringify call
    }).done(function (result) {
        ...
    }).error(function(error) {
        ...
    });
    

    【讨论】:

    • 好的,我们越来越近了。现在模型通过了,但所有属性都为空。我想我必须检查字段的定义。我确实在每个字段上都设置了 JsonProperty,但那里可能缺少某些东西。我更新了我的问题以包括模型的定义
    • 谢谢。这样做了。
    • AFAIK 您可以删除 JsonProperty 属性,因为 asp.net 核心与开箱即用的驼峰命名法兼容。 wildermuth.com/2016/06/27/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2021-02-27
    • 2021-09-12
    • 2017-07-02
    相关资源
    最近更新 更多