1

I have a Windows application which needs to call a Forms Authenticated MVC action. The problem is, I am not sure how to authenticate a call from a Windows application into a Forms Authenticated MVC application.

The following code returns the login page. Is there a way to allow the below code to work with Forms Authentication by whatever means, or do I need to create a new Web API project which uses Basic Authentication for this to work?

WebRequest req = WebRequest.Create("http://myurl/protectaction");
req.Credentials = new NetworkCredential("username", "password");

var res = req.GetResponse();

Thank you very much for your help,

Richard Hughes

4

1 回答 1

3

您可以使用CookieContainer来存储 LogOn 操作发出的 FormsAuthentication cookie。因此,基本上您将向 LogOn 操作发送第一个请求,然后为后续请求重用相同的 WebRequest 实例。

这样,您将只通过网络发送一次您的凭据。

例如:

var container = new CookieContainer();

var req = (HttpWebRequest)WebRequest.Create("http://myurl/account/logon");
req.CookieContainer = container;
req.Method = "POST";
using (var writer = new StreamWriter(req.GetRequestStream()))
{
    var data = HttpUtility.ParseQueryString(string.Empty);
    data["username"] = "john";
    data["password"] = "secret";
    writer.Write(data.ToString());
}
using (var res = req.GetResponse())
{
    // You could check here if login was successful
}

req = (HttpWebRequest)WebRequest.Create("http://myurl/protectedresource");
req.CookieContainer = container;
using (var res = req.GetResponse())
using (var reader = new StreamReader(res.GetResponseStream()))
{
    string result = reader.ReadToEnd();
    // do something with the protected resource
}
于 2013-01-18T14:37:00.907 回答