我写了一个测试登录页面(.aspx),它有一个Postback方法和第二个静态Webmethod调用。 javascript函数从“txt1”和“txt2”获取值并调用C#[WebMethod]
HTML:
<input type="text" id="txt1" />
<input type="text" id="txt2" />
//JS function sends values to C# WebMethod
PageMethods.ReceiveUsernamePassword(txt1.value, txt2.value);
C#:
[WebMethod]
public static string ReceiveUsernamePassword(string user, string pass)
{
File.AppendAllText(@"C:\Z\upjs.txt", user + " " + pass + " js " + "\r\n\r\n\r\n");
return "Success JS";
}
使用以下代码模拟POST的单独客户端应用程序。 URL指向localhost:1073 / PostData_Server / Default.aspx / ReceiveUsernamePassword:
using (WebClient client = new WebClient())
{
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("user", "user1");
reqparm.Add("pass", "password1");
byte[] responsebytes = client.UploadValues("http://local:1073/PostData_Server/Default.aspx", "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
我没有在我的测试客户端应用程序上获得“成功”或“成功JS”,而是接收整个HTML文档作为响应消息。服务器端也没有写入文本文件。我通过下载海报(https://addons.mozilla.org/en-us/firefox/addon/poster/)验证了我的客户端应用程序中的错误。它也接收整个HTML文档作为响应。我怎么能纠正这个?
答案 0 :(得分:0)
我想我会在这个问题上更新我的发现。事实证明,为了调用[WebMethod],ContentType必须设置为&#34; application / json&#34;。您也不能使用WebClient.UploadValues(),因为它不会让您更改ContentType。因此,为了发送正确的POST签名,您必须使用HttpWebRequest类。
另请注意:发送的用户名和密码必须是json格式!
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
myHttpWebRequest.Method = "POST";
myHttpWebRequest.ContentType = "application/json; encoding=utf-8";
using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
{
string json = "{user:\"user1\",pass:\"pass1\"}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responsebody = streamReader.ReadToEnd();
}