Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

c# - WebClient Does not automatically redirect

When logging the login process using Firebug i see that it is like this

POST //The normal post request
GET //Automatically made after the login
GET //Automatically made after the login
GET //Automatically made after the login

When making a post request using my code below it did not make the automatic GET requests that the browsers is doing.

MY WebClient Handler

using System;
using System.Net;

namespace Test
{
    class HttpHandler : WebClient
    {
        private CookieContainer _mContainer = new CookieContainer();

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = _mContainer;
            }
            return request;
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            var response = base.GetWebResponse(request);
            if (response is HttpWebResponse)
                _mContainer.Add((response as HttpWebResponse).Cookies);
            return response;
        }

        public void ClearCookies()
        {
            _mContainer = new CookieContainer();
        }
    }
}

Using Code

private static async Task<byte[]> LoginAsync(string username, string password)
{
    var postData = new NameValueCollection();
    var uri = new Uri(string.Format("http://{0}/", ServerName));

    postData.Add("name", username);
    postData.Add("password", password);

    return await HttpHandler.UploadValuesTaskAsync(uri, postData);
}

When trying to track the connection of my application it is only doing the POST Request and not the rest of GET requests. [THAT ARE MADE AUTOMATICALLY IN THE BROWSER]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try adding

request.AllowAutoRedirect = true;

right under the

var request = base.GetWebRequest(address);

It solved some similar problems for me, even though AllowAutoRedirect is supposed to be true by default.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...