在启动时设置Cookie(MVC .Net Core)

时间:2019-08-28 11:48:38

标签: c# .net vb.net cookies core

我正在将.NET Framework上的VB项目转换为C#.Net Core 2.2

在VB项目中,cookie设置在 Global.asax.vb 中:

Private Sub MvcApplication_BeginRequest(sender As Object, e As EventArgs) Handles Me.BeginRequest
    ' Redirect non-www. to www.
    If Not Request.Url.Host.StartsWith("www") AndAlso Not Request.Url.IsLoopback Then
        Dim builder = New UriBuilder(Request.Url)
        builder.Host = "www." & Request.Url.Host
        Response.StatusCode = 301
        Response.AddHeader("Location", builder.ToString)
        Response.End()
    End If

    //Cookie set here
    If HttpContext.Current.Request.Cookies("CH") Is Nothing Then
        Dim myCookie = New HttpCookie("CH")
        myCookie.Values("DeviceId") = System.Guid.NewGuid.ToString()
        myCookie.Expires = DateTime.Now.AddYears(45)
        HttpContext.Current.Response.Cookies.Add(myCookie)
    End If
End Sub

这是我的函数,用于返回C#中的cookie(基于Controller和httpContext):

    public static string getUserDeviceId(ControllerBase controller)
    {
        return controller.ControllerContext.HttpContext.Request.Cookies["DeviceID"];
    }

    public static string getUserDeviceIdFromContext(IHttpContextAccessor context)
    {
        return context.HttpContext.Request.Cookies["DeviceID"];
    }

我将通过使用以下命令获取“ id”:

string userDeviceId = BettingService.getUserDeviceId(this);
string userDeviceId = BettingService.getUserDeviceIdFromContext(_httpContext);

我如何以同样的方式在.Net core C#中设置此cookie?我想我将在Startup.cs中使用某个地方吗?

0 个答案:

没有答案