[英]Ajax Get call to ASP.NET MVC controller is treated as "NO ‘Access-Control-Allow-Origin’ error
I am having a ajax call in view script. 我在视图脚本中有一个ajax调用。 From this ajax call i am trying to get the data from controller action in same website. 通过这个ajax调用,我试图从同一网站的控制器操作中获取数据。 This is triggered as Cross No 'Access-Control-Allow-Origin' problem . 由于没有“访问控制允许来源”问题而被触发。
Java script code looks like Java脚本代码看起来像
function displaydata(id) {
$.ajax({
type: "GET",
async: true,
url: '@Url.Action("GetSomeData", "MyData")',
contentType: "application/json; charset=utf-8",
data: "id=" + id,
dataType: "json",
error: function (request, error) {
},
success: function (response) {
alert(response);
}
});
My MyDataController.cs looks like 我的MyDataController.cs看起来像
public class MyDataController : Controller
{
[HttpGet]
public string GetSomeData(int id)
{
// converted object to json string e.g. into jsonString
return jsonString;
}
}
This is working fine on local machine but after deployment actual site does not work. 这在本地计算机上工作正常,但是在部署之后,实际站点无法正常工作。 I receive the error No 'Access-control-allow-origin' found in header. 我收到标头中找不到错误“ Access-control-allow-origin”。
My question is that I am calling same server controller from which page is served so how it becomes the candidate for CORS issue? 我的问题是,我要从哪个页面调用相同的服务器控制器,因此它如何成为CORS问题的候选人? And how to solve it? 以及如何解决呢? as a technology I have website built in ASP.NET MVC razor view with Ajax and jquery. 作为一项技术,我有使用Ajax和jquery在ASP.NET MVC剃刀视图中构建的网站。
I did some more tests and found that if I deploy the WebSite in IIS in One of the VM it's working. 我进行了更多测试,发现如果我在其中一台VM中的IIS中部署WebSite,则它可以正常工作。 When I deploy it to cloud Web Apps then I get the same issue. 当我将其部署到云Web Apps时,会遇到相同的问题。
This helped me, although I don't do why some request from the same domain were getting blocked, just like yours. 这对我有所帮助,尽管我不这样做,为什么与您一样,来自同一个域的某些请求也被阻止了。
if (Request.UserHostName == "127.0.0.1")
{
Response.AddHeader("Access-Control-Allow-Origin", "*");
}
Add this lines into your web config file... And if it doesn't work let me know 将此行添加到您的Web配置文件中...如果不起作用,请通知我
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.5" />
<add name="ExtensionlessUrlHandler-Integrated-4.5" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.5" />
<remove name="WebDAV" />
</handlers>
</system.webServer>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.