开发者

Read an XML file from a website using forms based authentication

Is there a standard way to read a开发者_运维百科n XML file from a website that uses forms based authentication? We want to read the file into a desktop app.

thanks - dave


If you are talking about ASP.NET Forms Authentication this will be a two step process:

  1. Send an HTTP request to the login page sending the username and password and capturing the authentication cookie sent by the server
  2. Send an HTTP request to the script returning the XML file sending the authentication cookie along with the request

Here's an example using a custom WebClient:

public class CookieAwareWebClient : WebClient
{
    public CookieContainer Cookies { get; private set; }
    public CookieAwareWebClient()
    {
        Cookies = new CookieContainer();
    }

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

class Program
{
    static void Main()
    {
        using (var client = new CookieAwareWebClient())
        {
            client.UploadValues("http://www.foo.com/login.aspx", new NameValueCollection
            {
                { "username", "foo" },
                { "password", "secret" },
            });
            client.DownloadFile("http://www.foo.com/foo.xml", "foo.xml");
        }
    }
}

Of course in the real life things might be more complex because depending on the site you might need to send along ViewState and other ASP.NET specific crap along with the request.


post the credentials in an http request, on the response there will be an authentication cookie that you have to reuse for your next requests


You're going to have to use HTTPWebRequest/HTTPWebResponse in roughly the following steps:

1: Use a request to submit the username and password to the website 2: Save the Cookies (I assume the cookies will contain the ok that the login worked) 3: Use another request, including these cookies, to get the XML.

To find the code that for the initial request you will need to look at the source code of the login page to see the submission action, and then reproduce this through your request. You may be able to use fiddler or firebug etc to help working this out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜