Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind [FromRoute] and [FromBody] into one model

I have this endpoint

[HttpPost]
[Route("company/{companyid}/bankaccount")]
public async Task<Unit> AddCompanyBankAccount([FromBody]AddCompanyBankAccountCommand request)
{
    return await _mediator.Send(request);
}

And model

public class AddCompanyBankAccountCommand : IRequest<Unit>
{
    public Guid CompanyId { get; set; }
    public string BankName { get; set; } = String.Empty;
    public string AccountNo { get; set; } = String.Empty;
    public Guid CurrencyId { get; set; }
}  

I would like my endpoint to be something like POST contoso.com/company/{companyid}/bankaccount and I want to bind the {companyid} as Guid from route to the model. Is this possible WITHOUT custom model binding? I'm using NET 6.0

I also saw this website, but it's not working for me

like image 235
warheat1990 Avatar asked Sep 11 '25 23:09

warheat1990


1 Answers

You have to remove all FromXXX attributes from your controller method parameter and instead use both parameters within the class itself. It would look then something like this:

[HttpPost]
[Route("company/{companyId:guid}/bankaccount")]
public async Task<Unit> AddCompanyBankAccount(AddCompanyBankAccountCommand request) { ... }

public class AddCompanyBankAccountCommand : IRequest<Unit>
{
    [FromRoute]
    public Guid CompanyId { get; set; }

    [FromBody]
    public BankAccount Account { get; set; }
}

public class BankAccount
{
    public string BankName { get; set; } = String.Empty;
    public string AccountNo { get; set; } = String.Empty;
    public Guid CurrencyId { get; set; }
}

Be aware that you change the model you use inside (cause you have a nested class now) while the public interface (in swagger) stays the same.

Also ensure to set the type constraint for guid in your route if your property is a guid.

like image 84
Oliver Avatar answered Sep 14 '25 13:09

Oliver