WebClient.DownloadingString changing URL requested

前端 未结 1 939
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 11:23

If I put the URL at the browser, my server responds properly (a XML). Although, if this same URL pass through the WebClient.DownloadingString() method, something in the URL chan

1条回答
  •  醉梦人生
    2021-01-26 11:48

    You have to be sure that you're sending all the necessary data, cookies and request headers that the server is expecting.

    I advise you to install Fiddler Web Debugger and monitor successful requests from web browser, after that try to recreate such requests in your application.

    Maybe server is redirecting you to some error page because WebClient is not handling cookies. You can create your own version of WebClient and add cookie support. Create a class that inhertis from WebClient and override GetWebRequest method, there you have to add CookieContainer. Following is a simple implementation of WebClient that handles cookies:

    public class MyWebClient : WebClient
    {
        public CookieContainer CookieContainer { get; private set; }
    
        public MyWebClient()
        {
            this.CookieContainer = new CookieContainer();
        }
    
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = this.CookieContainer;
                (request as HttpWebRequest).AllowAutoRedirect = true;
            }
    
            return request;
        }
    }
    

    0 讨论(0)
提交回复
热议问题