通过上面的屏幕,我只想让你们知道,当我使用POST man ajax调用时,它按预期工作但当我尝试使用jQuery进行相同的AJAX调用时,它根本不工作,我的意思是我得到200 ok状态,但我对象上的所有属性都是空的,我确信这是因为在使用jQuery进行ajax调用时,标头未正确传递。
我尝试了很多方法,但却无法弄清楚为什么它不适合我。
下面是我尝试使用jQUery AJAX调用的代码。
$.ajax({
type: "POST",
url: "http://localhost:61146/MarkAndUnmarkCountry",
data: JSON.stringify({ obj: obj }),
dataType: "json",
async: true,
crossDomain: true,
headers: { 'Access-Control-Allow-Origin': '*'},
contentType: "application/json",
success: function (data) {
debugger;
if (data != null) {
}
}, error: function (err) {
debugger;
console.log(err.statusText);
}, complete: function () {
//DropDownUiBinding();
}
});
这是我的.NET CORE POST方法。
public class CountryController : Controller
{
private readonly ICountryApi _countryApi;
public CountryController(ICountryApi countryApi)
{
_countryApi = countryApi;
}
[Route("MarkAndUnmarkCountry")]
[HttpPost]
public async Task<IActionResult> MarkAndUnmarkCountry([FromBody] FavoriteRequestModel obj)
{
var resultJson = await _countryApi.MarkCountryFavourite(obj);
return Json(new { result = resultJson });
}
}
这是我的控制器,下面是我的启动配置
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});