在Web服务中读取Cookie

时间:2015-02-12 13:55:27

标签: c# web-services cookies

我正在尝试使用Web服务读取通过客户端在c#中发送的cookie。到目前为止我有这个代码,但我的网络服务不喜欢请求。有没有更好的方法通过Web服务读取cookie。只想以最佳实践方式去做。

int loop1, loop2;
HttpCookieCollection MyCookieColl;
HttpCookie MyCookie;

MyCookieColl = Request.Cookies;

// Capture all cookie names into a string array.
String[] arr1 = MyCookieColl.AllKeys;

// Grab individual cookie objects by cookie name. 
for (loop1 = 0; loop1 < arr1.Length; loop1++) 
{
   MyCookie = MyCookieColl[arr1[loop1]];
   Response.Write("Cookie: " + MyCookie.Name + "<br>");
   Response.Write ("Secure:" + MyCookie.Secure + "<br>");

   //Grab all values for single cookie into an object array.
   String[] arr2 = MyCookie.Values.AllKeys;

   //Loop through cookie Value collection and print all values. 
   for (loop2 = 0; loop2 < arr2.Length; loop2++) 
   {
      Response.Write("Value" + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
   }
}

2 个答案:

答案 0 :(得分:1)

使用以下代码

public String get_Cookie(String cookieName)
{
    HTTPRequest Request = System.Web.HttpContext.Current.Request;

    if (Request.Cookies.Get(cookieName) != null)
    {
        return HttpUtility.UrlDecode(Request.Cookies.Get(cookieName).Value);
    }
    else
    {
        return String.Empty;
    }
}

答案 1 :(得分:0)

我不知道我是否理解你的问题,但我这样做:

    public String get_Cookie(String cookieName)
            {
                HTTPRequest Request = this.Context.Request;//Added to better understanding.

                if (Request.Cookies.Get(cookieName) != null)
                {
                    return HttpUtility.UrlDecode(Request.Cookies.Get(cookieName).Value);
                }
                else
                {
                    return String.Empty;
                }
            }