In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you. NET 6 in the development of TodoList applications how to achieve DELETE request and HTTP request idempotence, the content is concise and easy to understand, absolutely can make your eyes bright, through the detailed introduction of this article, I hope you can get something.
Demand
Let's first explain the article about the PATCH request that we originally wanted to update. From the current experiment, if we follow the project structure of .NET 6 (that is, only one Program.cs is used to initialize the program), then the documents given by Microsoft have not been updated accordingly, and it is not possible to configure JsonPatch in the previous way. At present, someone has mentioned ISSUE: .net 6: JsonPatch in ASP.NET Core web API under Github Microsoft's official document Repo. And because the frequency of using PATCH is not high, so I will skip that article for a while and move on to see when Microsoft will solve this issue and then I will fill in the PATCH section.
In this article, let's take a look at the last common HTTP request type: DELETE.
target
Implement and verify that the application handles DELETE requests correctly. And make a brief introduction to the idempotency of HTTP request.
Principles and ideas
After the implementation of Create, Update and Get, our idea for the implementation of Delete is very clear. We need to create the Command of Delete and its Handler, and then send the request through Mediatr in Controller.
Realize
Create a new DeleteTodoList folder under Application/TodoList and create a new DeleteTodoListCommand:
DeleteTodoListCommand.cs
Using MediatR;using TodoList.Application.Common.Exceptions;using TodoList.Application.Common.Interfaces;namespace TodoList.Application.TodoLists.Commands.DeleteTodoList;public class DeleteTodoListCommand: IRequest {public Guid Id {get; set;}} public class DeleteTodoListCommandHandler: IRequestHandler {private readonly IRepository _ repository; public DeleteTodoListCommandHandler (IRepository repository) {_ repository = repository;} public async Task Handle (DeleteTodoListCommand request, CancellationToken cancellationToken) {var entity = await _ repository.GetAsync (request.Id) If (entity = = null) {throw new NotFoundException (nameof (TodoList), request.Id);} await _ repository.DeleteAsync (entity,cancellationToken); / / for the Delete operation, no actual objects are returned in the demonstration, and specific objects can be returned based on actual needs. The Unit object represents Void return Unit.Value;}} in MediatR
Add the interface handling of Delete to Controller:
TodoListController.cs
/ / omit other... [HttpDelete ("{id:guid}")] public async Task Delete (Guid id) {return ApiResponse.Success (await _ mediator.Send (new DeleteTodoListCommand {Id = id}));}
What may be worth emphasizing here is how DELETE operations of associated entities are handled in EntityFrameworkCore:
Open the Infrastructure/Migrations folder, and we can find this configuration in the .Designer.cs file generated by the Migration that migrated the domain entity:
/ / omit other... modelBuilder.Entity ("TodoList.Domain.Entities.TodoItem", b = > {b.HasOne ("TodoList.Domain.Entities.TodoList", "List") .WithMany ("Items") .HasForeignKey ("ListId") .OnDelete (DeleteBehavior.Cascade) .IsRequired (); b.Navigation ("List");})
You can see that the DeleteBehavior.Cascade behavior mode is configured in OnDelete. For more information about DeleteBehavior, please refer to Referential Constraint Action Options. There are actually a total of seven behavior patterns that can be set:
DeleteBehavior.Cascade
DeleteBehavior.NoAction
DeleteBehavior.Restrict
DeleteBehavior.SetNull
DeleteBehavior.ClientCascade
DeleteBehavior.ClientNoAction
DeleteBehavior.ClientSetNull
About these seven kinds of DeleteBehavior, you can refer to this blog post: Entity Framework Core association deletion, in which the blogger has carried out a more detailed experiment and summary.
You can explicitly configure DeleteBehavior according to your actual needs. In addition, the habit of observing the generated Migrations files is also a good way to learn some conventions or default configuration of EFCore.
Verification
Start the Api project and send the DELETE request:
Request
Response
And from the database, we can find that the TodoItem contained under this TodoList has also been deleted.
Summary
So far, we have covered the four commonly used HTTP requests through several examples, which will be written later on the HEAD request OPTION request and the legacy PATCH request. At the beginning of the next article, we will learn how to use FluentValidation for request parameter verification.
An introduction to the idempotency of HTTP requests
First of all, two concepts are clarified:
1. What is meant by whether the HTTP request is secure: if the corresponding resource entity remains unchanged after we execute the request, we call the request secure
two。 What is meant by HTTP request is idempotent: for the side effects after executing the request (that is, if the request is not secure, it will cause side effects), the side effects of executing the request once and executing multiple times are the same. We call the request idempotent, and it is obvious that the secure request must be idempotent.
With these two concepts in mind, let's look directly at this table and quickly get an idea of the security and idempotency of HTTP requests.
Since the PATCH method is not commonly used, the main focus is on the POST request and some PUT requests (for example, the updated field is calculated on the basis of the current field value, and this scenario is not idempotent, but it is generally not recommended to do this type of operation in Update. What is more recommended is to advance the computing logic to the interface response processing. Update the entity as a whole). Generally speaking, POST requests are used to create resources, and if there is no way to ensure the actual idempotency of the execution results, then the side effects of the request will be difficult to control and deal with.
How to ensure the idempotency of the interface?
Formally, because not all HTTP requests (here we can generalize to any type of interface request) are idempotent, and whether it is fault tolerance within applications or more stringent requirements for idempotency of requests caused by partitions between services (especially in distributed systems, where requests caused by partitions are retried), we need to design and implement interfaces Idempotent design is taken into account to improve the robustness of the interface.
Generally speaking, there are two ways to realize the idempotence of the interface: one is to limit the side effects of repeated calls through code logic, and the other is to ensure that the same request will not be called multiple times through the uniqueness of Token.
There are many ways to limit side effects through code logic: artificially restricting the repetition of requests from the front / interface level (such as button graying to disable clicks, etc.), by applying locks at the database level or using unique indexes, by applying locks during logic execution, and so on. This approach can only be aimed at some logical implementations that satisfy some judgments, and has its limitations.
The idea of ensuring idempotency through Token uniqueness is roughly like this: generate a globally unique Token and save it on the front-end page, send it to the backend together with Token when sending the request, and the backend first carries out Token verification, which deletes the old Token and generates a new Token after verification by sending the actual request or execution logic. Then the frontend refuses to continue execution the next time it comes with the saved old Token because the Token verification fails. This method is like SMS verification code. Only the first time you carry the verification code request, the request will be successful. After the backend determines that the first request is valid, the verification code will be set to invalid. Next time, you will not be able to continue to initiate the request with the same verification code. The example is not particularly appropriate, but it can be understood by analogy.
The above content is how to realize the idempotency of DELETE request and HTTP request in the development of TodoList application in .NET 6. have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.