ASP.NET中的请求和响应来自哪里?

时间:2011-07-07 15:46:46

标签: 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.
    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

请求和响应已经声明并且存在。

我正在开发一个Web服务而不是一个完整的网站。这就是我没有看到请求和响应已定义的原因吗?

我不明白为什么我这么麻烦。我在这里问了一个类似的问题: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时,它不会被添加。

2 个答案:

答案 0 :(得分:1)

请记住,在ASP.Net中,Page_Load()方法(以及网页上的任何其他方法)是类的成员,并且此类继承自another class。该基类的properties list包括RequestResponse

至于问题的后半部分,请查找Context变量。它已经以类似于网页中的请求和响应的方式为您的Web服务定义,它将允许您访问这些属性,包括请求中的任何cookie。

答案 1 :(得分:1)

您的问题是上面的代码属于继承自System.Web.UI.Page的类。这在此基类上有Request和Response对象,因此它们在派生类中可用。

标准Web服务将继承自System.Web.Services.WebService。这没有声明请求和响应。但是,它确实有一个“Context”属性,它是一个HTTPContext对象,它定义了Response和Request的属性。

我不确定服务中这些对象与标准网页相比可能存在哪些差异,但我猜核心内容是相同的。我不知道为什么他们没有在WebService类本身上定义它们......