Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In ASP.NET MVC Core, cookies can be verified on a subsequent request by using the code in the following steps:

  1. Include the Microsoft.AspNetCore.Authentication.Cookies package in the application.

  2. Configure the cookie middleware in the ConfigureServices method of the Startup class.

  3. Enable cookie authentication by calling the UseAuthentication method in the Configure method of the Startup class.

  4. Add the Authorize attribute to the Controller or action method that requires authentication.

  5. Use the HttpContext object to access the cookies and its values in subsequent requests.

Example code:

  1. In ConfigureServices method of Startup class, add the cookie middleware and its options:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "MyCookie"; options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Account/AccessDenied"; });

  2. In the Configure method of Startup class, use the authentication middleware:

    app.UseAuthentication();

  3. In your Controller or action method, add the Authorize attribute:

    [Authorize] public IActionResult MyAction() { // code here }

  4. To access cookies and its values, use HttpContext object:

    public IActionResult MyAction() { string cookieValue = Request.Cookies["MyCookie"]; // code here }

Note: The Request object is available in the Controller class.