Minimal API how to make FromBody accept both x-www-form-urlencoded and json?

247 Views Asked by At

Using ASP.NET Core 7 Minimal API:

[HttpPost("Create")]
public void Create([FromBody] User user)
{
}

Currently it is only able to accept application/x-www-form-urlencoded but I wish it can accept application/json as well.

1

There are 1 best solutions below

0
Yuning Duan On

Currently it is only able to accept application/x-www-form-urlencoded but I wish it can accept application/json as well.

Because of binding from form values is not natively supported in .NET 6 and 7.You can use custom model bindings to solve this:

app.MapPost("/customer", async (Customer customer) => {
    return Results.Ok(customer);
    
});

Custom model binding:

public class Customer
{
    public int Id { get; set; }
    public string Username { get; set; }

    public Customer(int id, string username)
    {
        Id = id;
        Username = username;
    }
    public static ValueTask<Customer?> BindAsync(HttpContext httpContext, ParameterInfo parameter)
    {
        if (httpContext.Request.ContentType == "application/x-www-form-urlencoded")
        {
            
            int.TryParse(httpContext.Request.Form["Id"], out var id);             
            return ValueTask.FromResult<Customer?>(
                new Customer(
                    id,
                    httpContext.Request.Form["Username"]

            )
        );
        }
        else
        {
            return  httpContext.Request.ReadFromJsonAsync<Customer>();
        }
    }
}

When I use x-www-form-urlencoded format to sent data: enter image description here

When I use Json format to sent data: enter image description here