【发布时间】:2011-09-30 14:20:37
【问题描述】:
我觉得这是一个相当简单的问题,但我似乎无法弄清楚。我了解如何使用 HttpWebRequest 创建 webRequest,将其发送到服务器并处理响应。
在微软的 ASP.NET 示例中,例如:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
// Get cookie from the current request.
HttpCookie cookie = Request.Cookies.Get("DateCookieExample");
// Check if cookie exists in the current request.
if (cookie == null)
{
sb.Append("Cookie was not received from the client. ");
sb.Append("Creating cookie to add to the response. <br/>");
// Create cookie.
cookie = new HttpCookie("DateCookieExample");
// Set value of cookie to current date time.
cookie.Value = DateTime.Now.ToString();
// Set cookie to expire in 10 minutes.
cookie.Expires = DateTime.Now.AddMinutes(10d);
// Insert the cookie in the current HttpResponse.
Response.Cookies.Add(cookie);
}
else
{
sb.Append("Cookie retrieved from client. <br/>");
sb.Append("Cookie Name: " + cookie.Name + "<br/>");
sb.Append("Cookie Value: " + cookie.Value + "<br/>");
sb.Append("Cookie Expiration Date: " +
cookie.Expires.ToString() + "<br/>");
}
Label1.Text = sb.ToString();
}
(来自http://msdn.microsoft.com/en-us/library/system.web.httpcookie.aspx)
Request 和 Response 已经被声明并且只是存在。
我正在开发一个网络服务而不是一个完整的网站。这就是我没有看到已经定义的请求和响应的原因吗?
我不明白为什么我会遇到这么多麻烦。我在这里问了一个类似的问题:How can I use ASP.NET to check if cookies are enabled without having a web page? 所以要么我遗漏了一些非常明显的东西,要么我试图解决的问题非常不标准。
感谢您的帮助。
编辑:
我正在尝试做这样的事情:
[WebMethod]
public bool CookiesEnabledOnClient()
{
bool retVal = true;
var request = (HttpWebRequest)WebRequest.Create("http://www.dealerbuilt.com");
request.Method = "Head";
var response = (HttpWebResponse)request.GetResponse();
HttpCookie Httpcookie = new HttpCookie("CookieAccess", "true");
response.Cookies.Add(Httpcookie);
//If statement checking if cookie exists.
return retVal;
}
但是 Cookies.Add 不会接受 Httpcookie,当我使用普通 cookie 时它不会被添加。
【问题讨论】:
标签: c# asp.net cookies httpwebrequest