Forms or Basic Authentication
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
You could use a CookieContainer to store the FormsAuthentication cookie that is emitted by the LogOn action. So basically you will send a first request to the LogOn action and then reuse the same WebRequest instance for subsequent requests.
This way you will be sending your credentials over the wire only once.
For example:
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
}
链接地址: http://www.djcxy.com/p/42078.html
上一篇: 错误:http查询字符串太长
下一篇: 表单或基本身份验证