您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān).NET 6開發(fā)TodoList應(yīng)用之如何實(shí)現(xiàn)PUT請(qǐng)求,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
PUT請(qǐng)求本身其實(shí)可說(shuō)的并不多,過(guò)程也和創(chuàng)建基本類似。在這篇文章中,重點(diǎn)是填上之前文章里留的一個(gè)坑,我們?cè)?jīng)給TodoItem定義過(guò)一個(gè)標(biāo)記完成的領(lǐng)域事件:TodoItemCompletedEvent,在SaveChangesAsync方法里做了一個(gè)DispatchEvents的操作。并且在DomainEventService實(shí)現(xiàn)IDomainEventService的Publish方法中暫時(shí)以下面的代碼代替了:
DomainEventService.cs
public async Task Publish(DomainEvent domainEvent) { // 在這里暫時(shí)什么都不做,到CQRS那一篇的時(shí)候再回來(lái)補(bǔ)充這里的邏輯 _logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name); }
在前幾篇應(yīng)用MediatR實(shí)現(xiàn)CQRS的過(guò)程中,我們主要是和IRequest/IRequestHandler打的交道。那么本文將會(huì)涉及到另外一對(duì)常用的接口:INotification/INotificationHandler,來(lái)實(shí)現(xiàn)領(lǐng)域事件的處理。
1.實(shí)現(xiàn)PUT請(qǐng)求;
2.實(shí)現(xiàn)領(lǐng)域事件的響應(yīng)處理;
實(shí)現(xiàn)PUT請(qǐng)求的原理和思路與實(shí)現(xiàn)POST請(qǐng)求類似,就不展開了。關(guān)于實(shí)現(xiàn)領(lǐng)域事件響應(yīng)的部分,我們需要實(shí)現(xiàn)INotification/INotificationHandler接口,并改寫Publish的實(shí)現(xiàn),讓它能發(fā)布領(lǐng)域事件通知。
我們拿更新TodoItem的完成狀態(tài)來(lái)舉例,首先來(lái)自定義一個(gè)領(lǐng)域異常NotFoundException,位于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.") { } }
創(chuàng)建對(duì)應(yīng)的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<TodoItem> { public Guid Id { get; set; } public string? Title { get; set; } public bool Done { get; set; } } public class UpdateTodoItemCommandHandler : IRequestHandler<UpdateTodoItemCommand, TodoItem> { private readonly IRepository<TodoItem> _repository; public UpdateTodoItemCommandHandler(IRepository<TodoItem> repository) { _repository = repository; } public async Task<TodoItem> 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; } }
實(shí)現(xiàn)Controller:
TodoItemController.cs
[HttpPut("{id:Guid}")] public async Task<ApiResponse<TodoItem>> Update(Guid id, [FromBody] UpdateTodoItemCommand command) { if (id != command.Id) { return ApiResponse<TodoItem>.Fail("Query id not match witch body"); } return ApiResponse<TodoItem>.Success(await _mediator.Send(command)); }
首先需要在Application/Common/Models定義一個(gè)泛型類,實(shí)現(xiàn)INotification接口,用于發(fā)布領(lǐng)域事件:
DomainEventNotification.cs
using MediatR; using TodoList.Domain.Base; namespace TodoList.Application.Common.Models; public class DomainEventNotification<TDomainEvent> : INotification where TDomainEvent : DomainEvent { public DomainEventNotification(TDomainEvent domainEvent) { DomainEvent = domainEvent; } public TDomainEvent DomainEvent { get; } }
接下來(lái)在Application/TodoItems/EventHandlers中創(chuàng)建對(duì)應(yīng)的Handler:
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<DomainEventNotification<TodoItemCompletedEvent>> { private readonly ILogger<TodoItemCompletedEventHandler> _logger; public TodoItemCompletedEventHandler(ILogger<TodoItemCompletedEventHandler> logger) { _logger = logger; } public Task Handle(DomainEventNotification<TodoItemCompletedEvent> notification, CancellationToken cancellationToken) { var domainEvent = notification.DomainEvent; // 這里我們還是只做日志輸出,實(shí)際使用中根據(jù)需要進(jìn)行業(yè)務(wù)邏輯處理,但是在Handler中不建議繼續(xù)Send其他Command或Notification _logger.LogInformation("TodoList Domain Event: {DomainEvent}", domainEvent.GetType().Name); return Task.CompletedTask; } }
最后去修改我們之前創(chuàng)建的DomainEventService,注入IMediator并發(fā)布領(lǐng)域事件,這樣就可以在Handler中進(jìn)行響應(yīng)了。
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<DomainEventService> _logger; public DomainEventService(IMediator mediator, ILogger<DomainEventService> 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)!; } }
啟動(dòng)Api項(xiàng)目,更新TodoItem的完成狀態(tài)。
請(qǐng)求
響應(yīng)
領(lǐng)域事件發(fā)布
關(guān)于“.NET 6開發(fā)TodoList應(yīng)用之如何實(shí)現(xiàn)PUT請(qǐng)求”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。