Unit.Value 来自 MediatR 返回状态代码 200 而不是 204

Unit.Value from MediatR is returning status code 200 instead of 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,因为我无法 return null。如果我的方法 return 类型是 Task<Unit>,我该如何 return null?或者除了使用 Task<Unit> 之外还有其他选择吗?

我的控制器

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);
    }
}

对于Mediatr,Unit等同于void,不是任何可以为空的对象。

我建议您将控制器更改为更具体的 return 类型:

public async Task<IActionResult> UpdateVendor([FromBody] UpdateVendorCommand request)
{
    _ = await _mediator.Send(request); // Don't care about the return type, it's void
    return NoContent();
}