sms*_*sms 3 asp.net ajax jquery web-services
当我调用我的webservice方法时,我收到以下错误.
Origin http://localhost:4165 is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)
当引用网络我得到像添加的解决方案Access-Control-Allow-Origin
我不知道在哪里添加这个.我的脚本是:
$(document).ready(function () {
$.ajax({
type: "Post", dataType: "json", contentType: "application/json; charset=utf-8",
url: "http://localhost:63384/ListWebService.asmx/HelloWorld", success: function (data) { alert(data.d); }, error: function (request, status, error) {
alert(request.responseText);
}
});
});
Run Code Online (Sandbox Code Playgroud)
我的webservice方法是:
[WebMethod]
public string HelloWorld()
{
return "Hello User";
}
Run Code Online (Sandbox Code Playgroud)
sms*_*sms 12
我找到了问题的答案.只需将以下内容添加到web.config文件即可
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
此外,如果您不希望全局设置它,那么您可以单独将其添加到您的操作方法,如下所示:
[WebMethod]
public string HelloWorld()
{
HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
return "Hello User";
}
Run Code Online (Sandbox Code Playgroud)