IHttpHandler将cookie发送回呼叫网站

时间:2012-04-24 17:12:36

标签: c# asp.net cookies httphandler

我有一个订购网站,需要在供应商网站上提出设置请求。 为此我使用WebHanlder(ashx文件)使用HttpContext对象在cXML中读取设置请求,该对象工作正常。

其中一个要求是我们发送一个名为“Buyer Cookie”的Cookie以及cXML 200 OK响应。

我遇到的问题是当我在上下文中创建一个cookie时。当我执行response.Output.Write().

时,它在订购网站中没有收到回复

我在写完后尝试使用response.Flush()但这仍然无效

如何将cookie发送回主叫站点?

这是我的代码:

订购网站

Stream stream = null;
byte[] bytes = Encoding.ASCII.GetBytes(File.ReadAllText(@"D:\Prototypes\HTTPPost\cXMLFiles\PunchOutSetupRequest.xml"));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:45454/PunchOutRequest.ashx");

webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.ContentLength = bytes.Length;

try
{
    stream = webRequest.GetRequestStream();
    stream.Write(bytes, 0, bytes.Length);
}
catch (Exception)
{
    throw;
}
finally
{
    if (stream != null)
        stream.Close();
}

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);

string r = responseReader.ReadToEnd();
var buy = webRequest.CookieContainer;
var buyer = response.Cookies["BuyerCookie"]; // This is always null

供应商网站

var request = context.Request;
StreamReader reader = new StreamReader(request.InputStream);

string text = reader.ReadToEnd();

POSetup setup = new POSetup();

if (setup.IsSetupRequestValid(text))
{
    HttpCookie cookie = new HttpCookie("BuyerCookie", "100");

    context.Response.Cookies.Add(cookie);
    context.Response.Output.Write(setup.GetOKResponse());
}

1 个答案:

答案 0 :(得分:1)

尝试添加此行:

webRequest.CookieContainer = new CookieContainer();

之后

webRequest.ContentLength = bytes.Length;