【发布时间】:2019-12-13 15:56:17
【问题描述】:
我需要向我的 asp.net 核心 web api 中定义的 post 方法发送一个 ajax 请求,如下所示:
// POST: api/Entreprise/Inscription
[HttpPost("Inscription")]
public IActionResult Post([FromBody] UserInfos value)
{
return Ok("value 1");
}
这是 UserInfos 模型:
public class UserInfos
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string domainName { get; set; }
public string phoneNumber {get;set;}
public string address { get; set; }
public string city { get; set; }
public string zip_code { get; set; }
}
我使用 postman 对其进行了测试,将标头设置为 'Content-Type':'application/json' 并在正文中选择 raw 并传递此 json 对象:
{
"firstname" :"ahmed",
"lastname":"haddad",
"email":"haddad-a@live.fr" ,
"domainName":"easyappointments-master" ,
"phoneNumber":"25276164",
"address":"ariana" ,
"city":"grand tunis",
"zip_code":"4100"
}
我让它工作,但是当我从 ajax 调用它时,我得到 BAD REQUEST 400,这是我的 ajax 代码:
var newData={
"firstname" :"ahmed",
"lastname":"haddad",
"email":"haddad-a@live.fr" ,
"domainName":"easyappointments-master" ,
"phoneNumber":"25276164",
"address":"ariana" ,
"city":"grand tunis",
"zip_code":"4100" ,
};
var dataJson= JSON.stringify(newData);
$.ajax({
url:'http://test.example.fr/wsexample/api/Entreprise/Inscription',
dataType:'json',
data:dataJson,
ContentType:'application/json',
type:'post',
success:function(data,status){
console.log('the request is '+status+' the data is '+data);
},
error:function(html,status,error){
console.log('the request is '+error);
}
});
注意:asp.net 核心 web api 和 ajax 代码在不同的服务器中,所以不同的域,我在 startup 中为我的域启用了对 CORS 的访问.cs ,因此通常不会引发问题。 我也向该网络服务发出了成功的获取请求
【问题讨论】: