我正在尝试对“Web 服务”进行跨域调用(我之所以这么说是因为它只是一个根据查询字符串值返回 XML 的站点)但没有运气。每次我提出请求时,我都会收到一个(401) Unauthorized
错误。但是,我可以将链接放在我的浏览器中,然后更改查询字符串以获取结果,因此我应该可以从我的计算机访问该站点。以下是我正在尝试使用的代码,有人可以提供任何建议吗?
对 Web 服务的调用源自页面视图中的 Ajax 调用。该代码粘贴在下面:
function GetProgramDetails() {
var searchItem = $('.searchbox').val();
var request = $.ajax({
type: 'POST',
url: '@Url.Action("compSearch", "Home")',
data:
{
searchFilter: searchItem,
url: location.protocol + '//' + location.host
},
dataType: 'html',
success: function (data) {
console.log(data);
alert(data);
},
error: function (data) {
console.log(data);
alert("Unable to process your resquest at this time.");
}
});
}
这会调用下面的视图控制器:
[HttpPost]
public string compSearch(string searchFilter, string url)
{
string results = string.Empty;
string URL =
"http://quahildy01/xRMDRMA02/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,'" +
searchFilter + "')";
try
{
WebRequest myWebRequest = WebRequest.Create(URL);
myWebRequest.Headers.Add("Access-Control-Allow-Origin", url);
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream myFileStreamResult = myWebResponse.GetResponseStream();
Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(myFileStreamResult, encoder);
results = readStream.ReadToEnd();
}
catch (Exception ex)
{
results = ex.InnerException.ToString();
}
return results;
}