0

这篇文章末尾的最终更新

我整天都在工作,但我无法让它工作:

private void button1_Click(object sender, EventArgs e)
{
    var loginUri = new Uri(@"http://localhost:5898/Account/Login");
    const string strLoginData = "Login=ojejq&Password=ojejqjejq&returnUrl=%2F";

    var cookie = GetAuthCookie(loginUri, strLoginData);
}

public CookieContainer GetAuthCookie(Uri loginUri, string data)
{
    var cookieJar = new CookieContainer();
    var request = (HttpWebRequest)WebRequest.Create(loginUri);
    request.Method = "POST";
    request.CookieContainer = cookieJar;
    request.ContentLength = data.Length;
    request.ContentType = "application/x-www-form-urlencoded";

    var myWriter = new StreamWriter(request.GetRequestStream());
    myWriter.Write(data);
    myWriter.Close();
    request.GetResponse();

    return cookieJar;
}

在我的ASP MVC应用程序中,我有一个/Account/Login POST控制器,它甚至没有被上面的代码击中。我究竟做错了什么?

编辑:我的 asp mvc 应用程序中的两个登录操作:

[AllowAnonymous]
public ActionResult Login()
{...}

[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel model, string returnUrl)
{...}

第二次更新:增加登录模式

public class LoginModel
{
    [Required]
    [Display(Name = "Login", ResourceType = typeof(NameResources))]
    [StringLength(16, ErrorMessageResourceName = "LoginLengthError", ErrorMessageResourceType = typeof(NameResources), MinimumLength = 4)]
    public string Login { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password", ResourceType = typeof(NameResources))]
    [StringLength(32, ErrorMessageResourceName = "PasswordLengthError", ErrorMessageResourceType = typeof(NameResources), MinimumLength = 8)]
    public string Password { get; set; }
}

第三次更新:我忘了提,在我的 web.config 中我设置了 cookieless="AutoDetect" 选项。不知道会不会有变化?

最后更新:首先,感谢你们的时间,所有试图帮助我的人都会获得支持。我发现问题不在于代码,而在于我的 Visual Studio 开发服务器。它以某种方式重定向了我的 button1 POST请求,在此过程中丢失了数据,并将该请求更改为GET请求。我知道,很奇怪,但代码没问题。感谢您的时间。

4

1 回答 1

5

我认为您应该尝试在“登录”中插入“用户名”:

const string strLoginData = "UserName=ojejq&Password=ojejqjejq&returnUrl=%2F";

也试试这个:

public CookieCollection GetAuthCookie(Uri loginUri, string data)
{
    var cookieJar = new CookieContainer();
    var request = (HttpWebRequest)WebRequest.Create(loginUri);
    request.Method = "POST";
    request.CookieContainer = cookieJar;
    request.ContentLength = data.Length;
    request.ContentType = "application/x-www-form-urlencoded";

    var myWriter = new StreamWriter(request.GetRequestStream());
    myWriter.Write(data);
    myWriter.Close();

    var webResponse = request.GetResponse() as HttpWebResponse;
    return webResponse.Cookies;
}
于 2012-10-09T19:53:58.220 回答