Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Cookie in WebApi Project by ASP.NET Core

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how ASP.NET Core uses Cookie in the WebApi project". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how ASP.NET Core uses Cookie in WebApi projects".

I. the role of Cookie

Cookie is usually used to store a piece of data about the user's information, which can be used to identify the logged-in user, and Cookie is stored on the client's browser. In most browsers, each Cookie is stored as a small file. Cookie is represented as a key / value pair that can be used to read, write, or delete Cookie.

Cookie can also be used in ASP.NET Core to maintain the reply state, and the Cookie containing the reply ID is sent to the client with each request.

Second, use Cookie in ASP.NET Core

We create a project for ASP.NET Core WebApi, and then test using Cookie in WebApi.

1. Use Cookie directly in the controller

Add a controller to the project to test the Cookie:

1.1.Setting Cookie

We can set the Cookie in the controller using the following code:

HttpContext.Response.Cookies.Append ("setCookie", "CookieValue")

If you want to set the expiration time of Cookie, we can use the overloading method of Append:

CookieOptions options = new CookieOptions (); / / set expiration time options.Expires = DateTime.Now.AddDays (1); HttpContext.Response.Cookies.Append ("setCookieExpires", "CookieValueExpires", options)

The method code in the controller is as follows:

Using System;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace CookieDemo.Controllers {[Route ("api/")] [ApiController] public class CookieTestController: ControllerBase {/ set Cookie / [HttpGet] [Route ("SetCookie")] public void Get () {HttpContext.Response.Cookies.Append ("setCookie", "CookieValue") CookieOptions options = new CookieOptions (); / / set expiration time options.Expires = DateTime.Now.AddDays (1); HttpContext.Response.Cookies.Append ("setCookieExpires", "CookieValueExpires", options);}

The CookieOptions class can specify the following additional properties when creating a Cookie:

Domain: used to specify the domain associated with the Cookie.

Expiration time: used to specify the expiration time of the Cookie.

Path: used to specify the Cookie path.

Security policy: used to specify whether Cookie is accessible through HTTPS.

HttpOnly: used to specify whether Cookie is available only to the server.

To run the program, we first visit the WeatherForecast controller and view the Cookie information:

We can see that there is only one Cookie information, and then the method SetCookie method:

We can see that there is already the Cookie information we just added.

1.2.Obtain Cookie

We can obtain Cookie information according to key:

HttpContext.Request.Cookies ["key"]

Let's look at the specific code:

Using System;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace CookieDemo.Controllers {[Route ("api/")] [ApiController] public class CookieTestController: ControllerBase {/ set Cookie / [HttpGet] [Route ("SetCookie")] public void Get () {HttpContext.Response.Cookies.Append ("setCookie", "CookieValue") CookieOptions options = new CookieOptions (); / / set expiration time options.Expires = DateTime.Now.AddDays (1); HttpContext.Response.Cookies.Append ("setCookieExpires", "CookieValueExpires", options) } / obtain the value of Cookie according to key / [HttpGet] [Route ("GetCookie")] public string GetCookid () {return HttpContext.Request.Cookies ["setCookie"];}

Run the program to see the effect:

1.3.Delete Cookie information

We can delete Cookie information based on key, as shown in the following code:

HttpContext.Response.Cookies.Delete ("key")

Next, let's look at the specific code:

Using System;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace CookieDemo.Controllers {[Route ("api/")] [ApiController] public class CookieTestController: ControllerBase {/ set Cookie / [HttpGet] [Route ("SetCookie")] public void Get () {HttpContext.Response.Cookies.Append ("setCookie", "CookieValue") CookieOptions options = new CookieOptions (); / / set expiration time options.Expires = DateTime.Now.AddDays (1); HttpContext.Response.Cookies.Append ("setCookieExpires", "CookieValueExpires", options) } / get the value of Cookie according to key / [HttpGet] [Route ("GetCookie")] public string GetCookid () {return HttpContext.Request.Cookies ["setCookie"] Delete Cookie / [HttpGet] [Route ("DeleteCookie")] public void DeleteCookie () {HttpContext.Response.Cookies.Delete ("setCookie");} according to key

To run the program, let's see the effect of obtaining Cookie:

Next, let's visit the method of deleting Cookie:

As you can see, the Cookie message has been deleted.

2. Encapsulate Cookie

In the above example, we are accessing the Response and Request of the HttpContext object before we can set, get, or delete the Cookie information. In a specific program, we usually encapsulate the operation of Cookie, and we can use the IHttpContextAccessor interface to access the HttpContext.HttpContextAccessor class in ASP.NET Core to implement this interface. Let's take a look at how to manipulate Cookie in the class library.

First, we need to register IHttpContextAccessor for dependency injection and add a singleton service of type HttpContextAccessor to the ConfigureServices method of the Startup class:

Public void ConfigureServices (IServiceCollection services) {/ / registered as singleton services.AddSingleton (); services.AddControllers ();}

Because we are using Cookie in a class library, we need to create a separate class library:

Next, create an API that encapsulates some operations of Cookie:

Namespace CookieDemo.Framework {public interface ICookieHelper {void SetCookie (string key, string value); void SetCookie (string key, string value, int expiresTime); string GetCookie (string key); void DeleteCookie (string key);}}

Then define a concrete implementation class to implement the ICookieHelper interface:

Using Microsoft.AspNetCore.Http;using System;namespace CookieDemo.Framework {public class CookieHelper: ICookieHelper {private readonly IHttpContextAccessor _ httpContextAccessor; / public CookieHelper (IHttpContextAccessor httpContextAccessor) {_ httpContextAccessor = httpContextAccessor via constructor } / delete the corresponding Cookie / key value public void DeleteCookie (string key) {_ httpContextAccessor.HttpContext.Response.Cookies.Delete (key) according to the key value } / get the value of Cookie according to the key value / key value / public string GetCookie (string key) {return _ httpContextAccessor.HttpContext.Request.Cookes [key] } / set cookie value / key value / value value public void SetCookie (string key, string value) {_ httpContextAccessor.HttpContext.Response.Cookies.Append (key, value) } / set Cookie and expiration time / key value / value value / expiration time Public void SetCookie (string key, string value, int expiresTime) {CookieOptions options = new CookieOptions () {Expires = DateTime.Now.AddMinutes (expiresTime)} in minutes _ httpContextAccessor.HttpContext.Response.Cookies.Append (key, value,options);}

Finally, we need to inject into the ConfigureServices method of Startup:

Public void ConfigureServices (IServiceCollection services) {/ / register as singleton services.AddSingleton (); / / register Cookie interface services.AddSingleton (); services.AddControllers ();}

Before adding a controller to access the Cookie:

Using CookieDemo.Framework;using Microsoft.AspNetCore.Mvc;namespace CookieDemo.Controllers {[Route ("api/CookieHelperTest")] [ApiController] public class CookieHelperTestController: ControllerBase {private readonly ICookieHelper _ helper; public CookieHelperTestController (ICookieHelper helper) {_ helper = helper } / set Cookie / [HttpGet] [Route ("SetCookie")] public void Get () {_ helper.SetCookie ("cookieHelperKey", "cookieHelperValue"); / / set expiration time _ helper.SetCookie ("cookieHelperExpiresKey", "cookieHelperExpitesValue", 10) } / get the value of Cookie according to key / [HttpGet] [Route ("GetCookie")] public string GetCookid () {return _ helper.GetCookie ("cookieHelperKey") Delete Cookie / [HttpGet] [Route ("DeleteCookie")] public void DeleteCookie () {_ helper.DeleteCookie ("cookieHelperKey") according to key;}

To run the program, first access the method of setting Cookie:

As you can see, we have set the Cookie information.

Next, visit to get the Cookie:

The corresponding value can be obtained according to key.

Last visit and delete Cookie:

As you can see, the cookie corresponding to key has been deleted.

Thank you for your reading, the above is the content of "how ASP.NET Core uses Cookie in WebApi project". After the study of this article, I believe you have a deeper understanding of how ASP.NET Core uses Cookie in WebApi project, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report