我正在尝试创建一个ASP.Net MVC端点以进行外部身份验证。我的想法是,我可以从控制台应用程序,WPF应用程序或其他任何东西调用端点,并使用MVC模式为我的服务,将JSON返回给经过身份验证的用户,通过属性检查身份验证等。我正在使用控制台应用程序现在只是因为它快速而简单。
到目前为止,我有这个:
在我的控制台应用中:
Public Sub MakeLoginRequest()
Dim address As Uri = New Uri("http://localhost:50536/Account/LogIn")
Dim request As HttpWebRequest = HttpWebRequest.Create(address)
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim loginModel As New LogOnModel With {.UserName = "Richard",
.Password = "Password1",
.RememberMe = False}
Dim jsonData As String = JsonConvert.SerializeObject(loginModel)
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(jsonData)
request.GetRequestStream.Write(bytes, 0, bytes.Count)
Dim response As HttpWebResponse = request.GetResponse()
End Sub
在我的控制器中:
<HttpPost()>
Public Function LogIn(model As LogOnModel) As ActionResult
If ModelState.IsValid Then
If Membership.ValidateUser(model.UserName, model.Password) Then
Dim cookie As HttpCookie = FormsAuthentication.GetAuthCookie(model.UserName, False)
cookie.Expires = DateTime.Now.AddMinutes(20)
Request.Cookies.Add(cookie)
Request.Cookies.Add(New HttpCookie("Barney", "Rubble"))
Return Content("Logged In Ok")
Else
Return New HttpUnauthorizedResult
End If
Else
Return New HttpUnauthorizedResult
End If
End Function
现在当我在控制台应用程序中检查响应时,从来没有任何cookie - 真正的Auth cookie和我的伪造Barney Rubble cookie实际上都没有出现!
但是......我在Chrome中拨打同一个电话并检查响应......两个Cookie都在那里!
有任何关于出了什么问题的想法吗?
答案 0 :(得分:2)
您需要在请求中设置CookieContainer,如下所述:
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx