2016-10-19 6 views
0

HttpListenerクラスをC#で使用しようとしています。クッキーが送信されないようにしながら、不要なSet-Cookieヘッダーを送信するようです。 HttpListenerContext contextを持つHttpListenerResponse不要なSet-Cookieヘッダーを追加する

、リクエストが何らかの方法で処理されている場合、応答部分は、そのように思える:

if (responseHeaders != null) 
     foreach (string header in responseHeaders.Keys) 
      context.Response.Headers.Add(header, responseHeaders[header]); 
    for (int i = 0; i < responseCookies.Count; i++) 
    { 
     context.Response.Headers.Add("Set-Cookie", responseCookies[i].ToHeaderString()); 
    } 
oWrite(response, responseEncoding); 
oClose(); 

そして、私の拡張メソッド、ToHeaderString()

public static string ToHeaderString(this Cookie c) 
    { 
     string s = c.Name + "=" + c.Value; 
     if (c.Path != null && c.Path != string.Empty) 
     { 
      s += "; path=" + c.Path; 
     } 
     if (c.Domain != null && c.Domain != string.Empty) 
     { 
      s += "; domain=" + c.Domain; 
     } 
     if (c.Expires != null) 
     { 
      s += "; expires=" + c.Expires.ToString("ddd, d MMM yyyy HH:mm:ss", new CultureInfo("en-US")) + " GMT"; 
     } 
     return s; 
    } 

responseHeadersは型であるDictionary<string, string>responseCookiesCookieCollectionです。クライアントに送信されるヘッダーとCookieの両方が入力されています。

Date:Wed, 19 Oct 2016 11:33:21 GMT 
Server:Microsoft-HTTPAPI/2.0 
Set-Cookie:username=yotam180; Max-Age=863999; Path=/, session=XCDbRv0fqbUwWC9g9xXL; Max-Age=863999; Path=/ 
Transfer-Encoding:chunked 

は、私がここで間違って何をやっている:

Cookie userCookie = new Cookie("username", _GET["__username"], "/"); 
userCookie.Expires = DateTime.Now.AddDays(10); 
_CONNECTION.responseCookies.Add(userCookie); 
Cookie userSession = new Cookie("session", ses, "/"); 
userSession.Expires = DateTime.Now.AddDays(10); 
_CONNECTION.responseCookies.Add(userCockie); 
_CONNECTION.responseCookies.Add(userSession); 

それでも、私は見ている応答は、ということでしょうか? HttpListenerResponseヘッダーを正しく使用していませんか?

ありがとうございます!

私はcontext.Response.Cookies.Add(..)を使ってみましたが、成功しませんでした。それが正しい方法ですか?または、ここで使用できるトリックはありますか?

答えて

0

まあ、私は最終的に私がそこで間違っていた場所を見つけました。

私が与えたコードの前に、初期化されていたはずの割り当てがありました。基本的にCookieCollection A = new CookieCollectionの代わりにCookieCoolection A = context.Response.Cookiesを割り当てると、context.Response.Cookiesのクッキーをコレクションに2回入力するようになりました。問題の原因は何かと思います。

関連する問題