gpt4 book ai didi

javascript - 如何跨域使用ajax调用asp.net web服务

转载 作者:行者123 更新时间:2023-11-30 05:47:20 25 4
gpt4 key购买 nike

我正在使用 javascript、html、css(跨平台技术)开发移动应用程序,我已经使用 asp .net 编写了一个 Web 服务,我想从 Web 服务获取数据并使用 javascript/jquery 显示到客户端。我们指向 Web 服务并显示结果,但这仅在 IE(Internet Explorer)中有效,我们得到的结果是服务器的“真实”响应,但在其他浏览器(Mozilla、chrome)中它不起作用,我们得到结果“false”作为来自服务器的响应。正如我期望的那样,结果在所有浏览器中都是“true”,但它没有发生。下面我给出了我使用过的所有代码。

网络服务.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

[WebMethod]
public bool GetValue(string id,string pwd)
{
string userid = "abc";
string password = "xyz";
if (userid==id && password==pwd)
{
return true;
}
else
{
return false;
}
}

}

网络配置

<?xml version="1.0"?>

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>

HTML 页面代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script>
function JsonTest2() {
jQuery.support.cors = true;
$.ajax({
type: 'POST',
url: "http://10.16.10.35/webservice_test/WebService.asmx/GetValue",
data: '{"id":"vipul","pwd":"borole"}',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
async: false,
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert('failure');
alert(msg);
}
});
}
</script>
</head>
<body>
<input id="Button1" type="button" value="button" onclick="javascript:JsonTest2();" />

</body>
</html>

请帮助我从所有浏览器调用此 Web 服务,我无法理解为什么它返回 false

最佳答案

您还需要为 POST 设置 Access-Control-Allow-Methods。

此外,您是否意识到使用 * 作为 Origin 允许任何人访问该服务?您可能想要使用适合实现 CORS 的库,例如 Thinktecture IdentityModel 库:

http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

查看 IIS/Url 选项(因为您似乎在 IIS 之外托管)。

关于javascript - 如何跨域使用ajax调用asp.net web服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17317374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com