1

I have a big problem when I using HttpWebRequest to get content from my blog.

First let's see the code

The request is made by a C# console application:

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);

Callback method

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
        }

    }

Now, this code don't work like I wish. It goes in my login method, save email on the session object and then makes a redirect to action index and here appears my big problem in the index method the object Session is null. Let's see the code

Login method

    [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);
    }

Index method

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

So, I will not receive the content from index method because I am not authorized. The code for save email on the session object is this:

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

Before to write here I searched on the net a solution for my problem and the following links didn't help me

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

Thank you in advance,

Marian

Community
  • 1
  • 1
roroinpho21
  • 732
  • 1
  • 11
  • 27
  • Maybe you should reshape your question, using only the code which is essential to your problem. – romanoza Aug 30 '14 at 09:46
  • The server side code works perfect. If I use a brawser or Fiddler tool the result is ok. I think my problem is when i build the HttpRequest object but in this mooment I don't know if I have made something wrong or if I have forgot to set a necesary property. – roroinpho21 Aug 30 '14 at 12:47

1 Answers1

0

Finally I solved the problem. It seems to keep session during redirect I should set request.CookieContainer = new CookieContainer();

roroinpho21
  • 732
  • 1
  • 11
  • 27