使用NetworkCredentials进行表单身份验证失败

时间:2012-10-09 14:55:20

标签: c# forms-authentication

这是我用来验证自己并采取行动的方法:

var uri = new Uri(@"http://localhost:5898/forums/AddPost/1");
var request = WebRequest.Create(uri);
request.Credentials = new CredentialCache { { new Uri(@"http://localhost:5898/Account/Login"), "Basic", new NetworkCredential("asdf", "ghijkl") } };
request.Method = "POST";

const string strPost = "Content=TestAplikacji&AddedValue=0";
StreamWriter myWriter = null;

request.ContentLength = strPost.Length;
request.ContentType = "application/x-www-form-urlencoded";

string response;
try
{
    myWriter = new StreamWriter(request.GetRequestStream());
    myWriter.Write(strPost);
}
catch
{

}
finally
{
    if (myWriter != null) myWriter.Close();
}

var objResponse = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(objResponse.GetResponseStream()))
{
    response = sr.ReadToEnd();
    sr.Close();
}

当代码执行时,在response我收到登录和密码的验证错误。但是我提供的登录名和密码("asdf", "ghijkl")满足了这些要求,这意味着http://localhost:5898/Account/Login没有收到我提供的凭据。我做错了什么?

1 个答案:

答案 0 :(得分:3)

我相信,如果要使用网络凭据,则应使用Windows身份验证/基本身份验证。

对于表单身份验证,您需要将usernamepassword发布到页面,就像浏览器将执行的操作一样,并从响应中读取身份验证Cookie。您应该使用此cookie进一步与经过身份验证的页面进行通信