I feel like this is a rather simple question, but I can’t seem to figure it out. I understand how to create a webRequest with HttpWebRequest, send it to the server, and handle the response.
In Microsoft’s ASP.NET examples like:
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();
}
(From http://msdn.microsoft.com/en-us/library/system.web.httpcookie.aspx)
Request and Response are already declared and just exist.
I am developing a web service instead of a full website. Is this why I do not see Request and Response already defined?
I do not understand why I am having so much trouble with this. I asked a similar question here: How can I use ASP.NET to check if cookies are enabled without having a web page? so either I am missing something completely obvious, or the problem I am trying to solve is very nonstandard.
I thank you for any help.
EDIT:
I’m trying to do something like this:
[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;
}
But Cookies.Add will not accept the Httpcookie and when I use a normal cookie it isn’t added.
Remember, in ASP.Net the Page_Load() method (and any other method on a web page) is a member of a class, and this class inherits from another class. The properties list of that base class includes both Request and Response.
As for the latter part of your question, look for the
Contextvariable. It is already defined for your web service in a manner similar to how Request and Response are available in a web page, and it will give you access to those properties, including any cookies in the request.