带有'Access-Control-Allow-Origin'的.NET Core + jQuery AJAX请求

时间:2018-05-11 12:29:05

标签: jquery .net-core asp.net-core-mvc asp.net-ajax asp.net-core-2.0

PostMan post request where I am passing Access-Control-Allow-Origin, and in below screen you can see that it's successfully passing the headers.

Fiddler request Headers where you can notice Access-Control Allow-Origin is passing in headers and also it's working fine.

通过上面的屏幕,我只想让你们知道,当我使用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?}");
                       });

0 个答案:

没有答案