问题描述
- ASP.NET自定义一个请求成功发送,为什么服务器无法拿到数据
-
场景:服务端套件要求客户端必须携带安全令牌,所以需要在客户端的请求报文头中植入一个安全令牌(也就是一个键值对),那么就不能使用HTML的表单进行提交,我需要自定义一个请求。
所以我用到了webrequest,代码如下:public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; //调用管控平台提供的客户端程序集的方法进行统一加密 string authToken = (new RESTClientExtension.Utility()).GenerateAuthorizationToken(); #region 把客户端页面的数据拼接成请求字符串 System.Text.StringBuilder data = new System.Text.StringBuilder(); data.AppendFormat("setuser={0}", context.Request.Form["setuser"].Replace(' ', '+')); data.AppendFormat("&No={0}", context.Request.Form["No"]); data.AppendFormat("&isKIA={0}", context.Request.Form["isKIA"]); data.AppendFormat("&Transfer={0}", context.Request.Form["Transfer"]); data.AppendFormat("&opinion={0}", context.Request.Form["opinion"]); data.AppendFormat("&isagree={0}", context.Request.Form["isagree"]); data.AppendFormat("&newname={0}", context.Request.Form["newname"]); #endregion string response = RequestUrl("http://10.73.199.26:8080/iRightResponse.ashx", data.ToString(), "POST", "text", "utf-8", authToken); context.Response.Write(response); } protected string RequestUrl(string url, string data, string method, string contentType, string charset,string authToken) { WebRequest request = WebRequest.Create(url); request.Method = method; request.ContentType = contentType; request.Headers.Add("charset:" + charset); request.Headers.Add("Authorization", authToken); Encoding encoding = Encoding.GetEncoding(charset); if (data != null) { byte[] buffer = encoding.GetBytes(data); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } else { request.ContentLength = 0; } using (HttpWebResponse wr = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(wr.GetResponseStream(), encoding)) { return reader.ReadToEnd(); } } } public bool IsReusable { get { return false; } }
}
请求时发送成功了,因为有了服务器的返回消息,但是返回消息显示表明,服务器无法拿到"No"的值,或者No的值为空,而且我也对比了正常请求和这种自定义请求的请求报文,没有区别,但是正常请求可以成功提交。坐等高人指点,谢谢
时间: 2024-12-21 06:38:41