开发者

ASP.Net MVC Cookies in Console App

I'm trying to create an ASP.Net MVC endpoint to authenticate externally. The idea is so that I can call the endpoint from a console app, WPF app or whatever, and use the MVC pattern for my service, returning JSON to authenticated users, checking authentication via the attribute etc. I'm using a console app for now just because it's quick and simple.

I have this so far:

In my console app:

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"
开发者_StackOverflow社区
        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

In my controller:

<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

Now when I inspect the response in the console app, there are never any cookies - neither the real Auth cookie, nor my bogus Barney Rubble cookie actually appear!

However... I make the same call in Chrome and inspect the response... and both cookies are there!

Anyone any ideas as to what's going wrong?


You need to set a CookieContainer on your request as described here:

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜