C# - 连接:在HttpWebRequest重定向期间未发送保持活动标头

时间:2014-08-30 09:15:49

标签: c# httpwebrequest

当我使用HttpWebRequest从我的博客中获取内容时,我遇到了一个大问题。

首先让我们看看代码

请求由C#控制台应用程序发出:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/MyBlog2014/Security/Login");
        request.ProtocolVersion = HttpVersion.Version10;
        var data = "Email=myemail&Password=1234567&keepMeOn=false";
        byte[] send = Encoding.Default.GetBytes(data);
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
        request.Headers.Add("Accept-Language: ro-RO,ro;q=0.8,en-US;q=0.6,en;q=0.4");
        request.Headers.Add("Cache-Control: max-age=0");
        request.KeepAlive = true;
        request.UnsafeAuthenticatedConnectionSharing = true;
        request.ServicePoint.ConnectionLimit = 1;
        request.ServicePoint.UseNagleAlgorithm = false;
        request.ServicePoint.Expect100Continue = false;

        request.Method = "POST";
        request.UserAgent =
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = send.Length;
        request.AllowAutoRedirect = true;
        Stream sout = request.GetRequestStream();
        sout.Write(send, 0, send.Length);
        sout.Flush();
        sout.Close();
        Console.WriteLine("\nThe HTTP request Headers for the first request are: \n{0}", request.Headers);

        IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(RespCallback), request);

回调方法

static void RespCallback(IAsyncResult asynchronousResult)
    {
        try
        {

            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            WebResponse res = request.GetResponse();
            var stream = new StreamReader(res.GetResponseStream());
            Console.WriteLine(stream.ReadToEnd());
            stream.Close();
            res.Close();
            Console.WriteLine();
        }
        catch (WebException e)
        {
            //do something
        }
        catch (Exception e)
        {
            //do something
        }

    }

现在,这段代码并不像我希望的那样工作。它进入我的登录方法,在会话对象上保存电子邮件,然后重定向到操作索引,这里出现了我在索引方法中的大问题,对象Session为空。 我们来看看代码

登录方式

    [HttpPost]
    public ActionResult Login(LoginDto login)
    {
        // if email and password are ok the save email on the sessio 
        // then reirect to index
        //else show error messages(s)  return View(login);
    }

索引方法

[AuthorizeUser(false)]
    public ActionResult Index(int pag = 1)
    {
        //I built the model
        return View(new HomePageModel
        {
            CUrrentPage = pag,
            Articles = model,
            MaxPage = totalpagesArticles
        });
    } 

因此,我不会收到索引方法的内容,因为我没有获得授权。 会话对象上保存电子邮件的代码如下:

public void SaveDetaliiUser(SessionUserDetails userDetails)
    {
        HttpContext.Current.Session[SessionDetaliiUtilizator] = userDetails;
    }

在此之前我在网上搜索了我的问题的解决方案,以下链接对我没有帮助

How to send KeepAlive header correctly in c#?

C# - Connection: keep-alive Header is Not Being Sent During HttpWebRequest

Keep a http connection alive in C#?

http://social.msdn.microsoft.com/Forums/en-US/87bc7029-ce23-438a-a767-f7c32dcc63a7/how-to-keep-connection-live-while-using-httpwebrequest?forum=netfxnetcom

提前谢谢你,

玛丽安

1 个答案:

答案 0 :(得分:0)

最后我解决了这个问题。它似乎在重定向期间保持会话我应该设置request.CookieContainer = new CookieContainer();