jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
11.11k stars 1.18k forks source link

Empty response body #423

Closed klyse closed 5 years ago

klyse commented 5 years ago

Hi,

I would like to return a void (empty) object on operations that do not require a response body in Asp.Net core.

I use MediatR for MVC with CQRS.

My command class:

public class PatchCustomerCommand : IRequest<Unit>
{
    public string TenantCode { get; set; }
    public JsonPatchDocument<PatchCustomerDao>  Customer { get; set; }
}

the handler class:

public class PatchCustomerCommandHandler : IRequestHandler<PatchCustomerCommand, Unit>
{
    ....
    public async Task<Unit> Handle(PatchCustomerCommand request, CancellationToken cancellationToken)
    {
        ....
        return Unit.Value;
    }
}

And my controller:

[HttpPatch("{tenantCode}")]
public async Task<ActionResult<object>> Patch(string tenantCode, [FromBody] JsonPatchDocument<PatchCustomerDao> value)
{
    return Ok(await _mediator.Send(new PatchCustomerCommand
                                   {
                                       TenantCode = tenantCode,
                                       Customer = value
                                   }));
}

Expected json result: "" (empty body)

Actual result: "{}" (two curly brackets)

TechDetails: TargetFramework: netcoreapp2.2 MediatrNugetPackage: MediatR.Extensions.Microsoft.DependencyInjection MediatrNugetPackageVersion: 7.0.0

Thank you :)

jbogard commented 5 years ago

You can return instead of void, but Unit. I can't use void as a first-class type, so the Unit type can represent "null" or "nothing"