Home > Blockchain >  Bind [FromRoute] and [FromBody] into one model
Bind [FromRoute] and [FromBody] into one model

Time:03-07

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/123/bankaccount and I want to bind the 123 id from route to the model. Is this possible WITHOUT custom model binding? I'm using NET 6.0

I also saw this enter image description here

But, in your question, When you post xxxxx/company/123/bankaccount, you want bind 123 from route to the model, Because the type of 123 is int, the type of CompanyId is Guid, Their types are differnet and You cannot convert Guid to int, So you can't bind them.

CodePudding user response:

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.

CodePudding user response:

try this

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

you can even send Get request, but in this case only id will be assign.

  • Related