MVC的ASP.NET核心POST
问题描述:
我试图从我的ASP.NET核心应用程序从客户端到MVC控制器发出一个简单的POST请求。问题是,即使我已经正确设置了ajax调用(我认为),负载总是以表单url的形式提交,并且我的模型在服务器上结束为null。这里是我的设置:MVC的ASP.NET核心POST
控制器操作定义:
[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=
通知有效载荷在请求的结束。它不是JSON格式,即使我传递一个普通的JS对象并将contentType指定为application/json。我猜这就是为什么我的模型在服务器上始终为空。
我一直盯着这几个小时了,看不到问题出在哪里。任何输入是不胜感激。
谢谢。
答
您的模型未序列化为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,但也许在那里丢失了一些东西。我更新了我的问题,包括模型的定义 – dpdragnev
谢谢。这做到了。 – dpdragnev
AFAIK您可以删除JsonProperty属性,因为asp.net核心与开箱即用的骆驼命名兼容。 https://wildermuth.com/2016/06/27/Converting-ASP-NET-Core-1-0-RC2-to-RTM-位 – Operatorius