在使用KendoDataSource期间,从LocalHost到同一域MVC控制器的Ajax调用



我正试图访问域内IIS服务器上的MVC控制器中的数据。我收到这个错误

"No 'Access-Control-Allow-Origin' header is present on the requested resource.
 Origin 'http://localhost:22205' is therefore not allowed access. " 

这是我的ajax调用:

binDropDownDataSource: new kendo.data.DataSource({
  autobind: false,
  serverFiltering: true,
  dataType: "json",
  crossDomain: true,
  transport: {
    read: {
      cache: false,
      //url: "/LogisticsWebApp/Requisitions/GetBins", This works if unremarked
      url: "https://www.MyDomain.com/LogisticsWebApp/requisitions/getsites",
      xhrFields: {
        withCredentials: true
      },
      data: function () {
        {
          siteCode: viewModel.site.SiteCode,
          shopCode: viewModel.binShopBlock.ShopCode
        };
      }
    }
  }
})

这是我的控制器:

public JsonResult GetBins(string siteCode, string shopCode)
{
    var lookups = new Lookups();
    var data = lookups.GetBins(siteCode,shopCode);
    return Json(data, JsonRequestBehavior.AllowGet);
}   

我希望能够使用一个应用程序作为我的数据层,但需要能够针对它进行开发。

如果您需要此特定方法,您可以将GetBins操作更改为:

public JsonResult GetBins(string siteCode, string shopCode)
{
    HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
    var lookups = new Lookups();
    var data = lookups.GetBins(siteCode,shopCode);
    return Json(data, JsonRequestBehavior.AllowGet);
} 

编辑

如果你需要通过控制器中没有的方法来做到这一点,你必须使用:

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

添加标头("Access Control Allow Origin","*"

System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With");

最新更新