MediatR 的 Unit.Value 返回状态代码 200 而不是 204
考虑以下代码,
public async Task<Unit> Handle(UpdateVendorCommand request, CancellationToken cancellationToken)
{
var vendor = await _context.Vendor.FindAsync(request.Id);
if (vendor is null)
throw new KeyNotFoundException();
_mapper.Map(request, vendor);
await _context.SaveChangesAsync();
return Unit.Value;
}
我收到状态代码 200 而不是 204,因为我无法返回 null
。如果我的方法返回类型为 Task
,如何返回 null
?或者除了使用 Task
之外还有其他选择吗?
我的控制器
public class UpdateVendorController : ControllerBase
{
private readonly IMediator _mediator;
public UpdateVendorController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPut]
[Route("vendor")]
[SwaggerOperation(Tags = new[] { "Vendor" })]
public async Task<Unit> UpdateVendor([FromBody] UpdateVendorCommand request)
{
return await _mediator.Send(request);
}
}
consider following code
public async Task<Unit> Handle(UpdateVendorCommand request, CancellationToken cancellationToken)
{
var vendor = await _context.Vendor.FindAsync(request.Id);
if (vendor is null)
throw new KeyNotFoundException();
_mapper.Map(request, vendor);
await _context.SaveChangesAsync();
return Unit.Value;
}
I'm getting status code 200 instead of 204 because I can't return null
. How do I return null
if my method return type is Task<Unit>
? Or is there any alternative beside using Task<Unit>
?
My Controller
public class UpdateVendorController : ControllerBase
{
private readonly IMediator _mediator;
public UpdateVendorController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPut]
[Route("vendor")]
[SwaggerOperation(Tags = new[] { "Vendor" })]
public async Task<Unit> UpdateVendor([FromBody] UpdateVendorCommand request)
{
return await _mediator.Send(request);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于 Mediatr 来说,Unit 相当于 void,而不是任何类型的可以为 null 的对象。
我建议您将控制器更改为更具体的返回类型:
For Mediatr, Unit is equivalent to void, not any kind of object that can be nullable.
I'd suggest you change the controller to be more specific in return types: