C# ASP.NET中的请求和响应来自哪里?
我觉得这是一个相当简单的问题,但我似乎无法理解。我了解如何使用HttpWebRequest创建webRequest,将其发送到服务器,并处理响应 在Microsoft的ASP.NET示例中,例如:C# ASP.NET中的请求和响应来自哪里?,c#,asp.net,cookies,httpwebrequest,C#,Asp.net,Cookies,Httpwebrequest,我觉得这是一个相当简单的问题,但我似乎无法理解。我了解如何使用HttpWebRequest创建webRequest,将其发送到服务器,并处理响应 在Microsoft的ASP.NET示例中,例如: protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); // Get cookie from the current request. Http
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();
}
但是Cookies.Add不会接受Httpcookie,当我使用普通cookie时,它不会被添加。请记住,在ASP.Net中,Page_Load()方法(以及网页上的任何其他方法)是类的成员,该类继承自。该基类的类型包括和
至于问题的后半部分,请查找变量。它已经以类似于网页中请求和响应的方式为您的web服务定义,并且它将允许您访问这些属性,包括请求中的任何cookie。您的问题是,上面的代码位于继承自的类中。这个基类上有请求和响应对象,因此它们在派生类中可用 标准web服务将从继承。它没有声明请求和响应。但是,它确实有一个“上下文”属性,它是一个定义响应和请求属性的对象
我不确定与标准网页相比,服务中的这些对象可能有什么不同,但我猜核心内容是相同的。我不知道他们为什么不在WebService类本身上定义它们…因此,因为我没有使用事件驱动方法,所以我不会继承响应或请求?@Nathan:不,这是因为您不在从Page派生的类中。我认为乔尔把事情搞糊涂了,提到了页数。忘记这一点,记住您的网页继承自System.web.UI.PageI,但我不会使用网页。我只是在写一个web服务。有了这个,我是否需要遵循一个特殊的协议来让我的网络请求和类似的行为与页面的行为相同?@Joel-这正是我想要的。谢谢,这正是我需要的。也谢谢你,没问题。当我发布我的答案时,我并没有注意到Joel更新了他的答案,提到了一些关于服务的内容,但很高兴你还是很感激
[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;
}