In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to implement PUT requests in the development of TodoList applications in .NET 6. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Demand
The PUT request itself is not much to say, and the process is basically similar to creating it. In this article, the focus is to fill in a hole left in the previous article, where we once defined a domain event marked as complete for TodoItem: TodoItemCompletedEvent, which did a DispatchEvents operation in the SaveChangesAsync method. And the following code is temporarily replaced in the Publish method of DomainEventService implementing IDomainEventService:
DomainEventService.cs
Public async Task Publish (DomainEvent domainEvent) {/ / do nothing here for the time being, and then come back to add the logic _ logger.LogInformation ("Publishing domain event. Event-{event}", domainEvent.GetType () .Name);} in the CQRS article.
In the previous articles, we mainly dealt with IRequest/IRequestHandler in the process of implementing CQRS with MediatR. Then this article will cover another pair of commonly used interfaces: INotification/INotificationHandler, to implement the handling of domain events.
target
1. Implement PUT request
two。 Implement response handling of domain events
Principles and ideas
The principles and ideas for implementing PUT requests are similar to those for POST requests, so they will not be expanded. For the part about implementing domain event response, we need to implement the INotification/INotificationHandler interface and rewrite the implementation of Publish so that it can publish domain event notifications.
Implement PUT request
Let's take updating the completion status of TodoItem as an example. First, we define a domain exception NotFoundException, which is located in Application/Common/Exceptions:
NotFoundException.cs
Namespace TodoList.Application.Common.Exceptions;public class NotFoundException: Exception {public NotFoundException (): base () {} public NotFoundException (string message): base (message) {} public NotFoundException (string message, Exception innerException): base (message, innerException) {} public NotFoundException (string name, object key): base ($"Entity\" {name}\ "({key}) was not found.") {}}
Create the corresponding Command:
UpdateTodoItemCommand.cs
Using MediatR;using TodoList.Application.Common.Exceptions;using TodoList.Application.Common.Interfaces;using TodoList.Domain.Entities;namespace TodoList.Application.TodoItems.Commands.UpdateTodoItem;public class UpdateTodoItemCommand: IRequest {public Guid Id {get; set;} public string? Title {get; set;} public bool Done {get; set;} public class UpdateTodoItemCommandHandler: IRequestHandler {private readonly IRepository _ repository; public UpdateTodoItemCommandHandler (IRepository repository) {_ repository = repository;} public async Task Handle (UpdateTodoItemCommand request, CancellationToken cancellationToken) {var entity = await _ repository.GetAsync (request.Id); if (entity = = null) {throw new NotFoundException (nameof (TodoItem), request.Id) } entity.Title = request.Title? Entity.Title; entity.Done = request.Done; await _ repository.UpdateAsync (entity, cancellationToken); return entity;}}
Implement Controller:
TodoItemController.cs
[HttpPut ("{id:Guid}")] public async Task Update (Guid id, [FromBody] UpdateTodoItemCommand command) {if (id! = command.Id) {return ApiResponse.Fail ("Query id not match witch body");} return ApiResponse.Success (await _ mediator.Send (command));} publication and response to domain events
First, you need to define a generic class in Application/Common/Models and implement the INotification interface to publish domain events:
DomainEventNotification.cs
Using MediatR;using TodoList.Domain.Base;namespace TodoList.Application.Common.Models;public class DomainEventNotification: INotification where TDomainEvent: DomainEvent {public DomainEventNotification (TDomainEvent domainEvent) {DomainEvent = domainEvent;} public TDomainEvent DomainEvent {get;}}
Next, create the corresponding Handler in Application/TodoItems/EventHandlers:
TodoItemCompletedEventHandler.cs
Using MediatR;using Microsoft.Extensions.Logging;using TodoList.Application.Common.Models;using TodoList.Domain.Events;namespace TodoList.Application.TodoItems.EventHandlers;public class TodoItemCompletedEventHandler: INotificationHandler {private readonly ILogger _ logger; public TodoItemCompletedEventHandler (ILogger logger) {_ logger = logger;} public Task Handle (DomainEventNotification notification, CancellationToken cancellationToken) {var domainEvent = notification.DomainEvent / / here we only do log output, and business logic processing is carried out as needed in actual use, but it is not recommended to continue to Send other Command or Notification _ logger.LogInformation ("TodoList DomainEvent: {DomainEvent}", domainEvent.GetType () .Name); return Task.CompletedTask;} in Handler.
Finally, modify the DomainEventService we created earlier, inject IMediator, and publish domain events so that we can respond in Handler.
DomainEventService.cs
Using MediatR;using Microsoft.Extensions.Logging;using TodoList.Application.Common.Interfaces;using TodoList.Application.Common.Models;using TodoList.Domain.Base;namespace TodoList.Infrastructure.Services;public class DomainEventService: IDomainEventService {private readonly IMediator _ mediator; private readonly ILogger _ logger; public DomainEventService (IMediator mediator, ILogger logger) {_ mediator = mediator; _ logger = logger;} public async Task Publish (DomainEvent domainEvent) {_ logger.LogInformation ("Publishing domain event. Event-{event} ", domainEvent.GetType () .Name); await _ mediator.Publish (GetNotificationCorrespondingToDomainEvent (domainEvent));} private INotification GetNotificationCorrespondingToDomainEvent (DomainEvent domainEvent) {return (INotification) Activator.CreateInstance (typeof (DomainEventNotification) .MakeGenericType (domainEvent.GetType ()), domainEvent)!;}} Verification
Start the Api project and update the completion status of TodoItem.
Request
Response
Domain event release
This is the end of the article on "how to implement PUT requests in the development of TodoList applications in .NET 6". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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.