ele*_*y19 5 c# https web-services httpwebrequest bad-request
我正在尝试使用ASP.NET页面测试Web服务调用,该页面创建一个包含用户名和密码字段以及"提交"按钮的表单.(我正在使用的jQuery和.js文件都包含在head元素的脚本标记中.)
"提交"按钮调用在C#代码隐藏文件中创建的函数,该函数调用单独的JavaScript文件.
protected void mSubmit_Click(object sender, EventArgs eventArgs)
{
String authenticate = String.Format("Authentication(\"{0}\",\"{1}\");", this.mUsername.Text,this.mPassword.Text);
Page.ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", authenticate, true);
}
Run Code Online (Sandbox Code Playgroud)
JavaScript函数Authenticate使用jQuery和Ajax对不同的服务器进行Web服务调用,发送JSON参数并期望返回JSON作为响应.
function Authentication(uname, pwd) {
//gets search parameters and puts them in json format
var params = '{"Header":{"AuthToken":null,"ProductID":"NOR","SessToken":null,"Version":1},"ReturnAuthentication":true,"Password":"' + pwd + '","Username":"' + uname + '",”ReturnCredentials”:false }';
var xmlhttp = $.ajax({
async: false,
type: "POST",
url: 'https://myHost.com/V1/Identity/Authenticate',
data: params,
contentType: 'application/json'
});
alert(xmlhttp.statusText);
alert(xmlhttp.responseText);
return;
}
Run Code Online (Sandbox Code Playgroud)
但是,因为我正在调用的Web服务与ASP.NET,C#和JavaScript文件位于不同的服务器上,所以我没有得到statusText或responseText警告.
不知何故,没有任何东西被发送到Web服务,我没有得到任何回报,甚至没有错误.我尝试在beforeSend属性中添加一个函数,但是没有触发.我需要一种特殊的方式来处理调用服务器外的Web服务吗?
UPDATE!
在jjnguy,Janie和Nathan的建议下,我现在正在尝试使用HttpWebRequest对Web服务进行服务器端调用.使用jjnguy的一些代码以及这个问题的代码,我想出了这个.
public static void Authenticate(string pwd, string uname)
{
string ret = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myhost.com/V1/Identity/Authenticate");
request.ContentType = "application/json";
request.Method = "POST";
string data = "{\"Header\":{\"AuthToken\":null,\"ProductID\":\"NOR\",\"SessToken\":null,\"Version\":1},\"ReturnAuthentication\":true,\"Password\":\"" + pwd + "\",\"Username\":\"" + uname + "\",\"ReturnCredentials\":false }'";
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (response)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
ret = reader.ReadToEnd();
}
Console.WriteLine(ret);
}
Run Code Online (Sandbox Code Playgroud)
但是,(400) Bad Request当我尝试从HttpWebRequest获取响应时,我从远程服务器收到错误.异常的Response属性{System.Net.HttpWebResponse}的值表示,Status属性的值为ProtocolError.我很确定这是因为URL使用的是HTTP SSL协议.除了让ASP.NET页面URL以HTTPS(不是选项)开头之外,我该怎么做才能解决这个问题?
事实证明,我在更新中发布的代码是正确的,我只是有一个拼写错误,并且数据字符串中的一个设置不正确。
string data = "{\"Header\":{\"AuthToken\":null,\"ProductID\":\"NOR\",\"SessToken\":null,\"Version\":1},\"ReturnAuthentication\":true,\"Password\":\"" + pwd + "\",\"Username\":\"" + uname + "\",\"ReturnCredentials\":true}";
Run Code Online (Sandbox Code Playgroud)