Skip to content

The search box in the website knows all the secrets—try it!

For any queries, join our Discord Channel to reach us faster.

JasperFx Logo

JasperFx provides formal support for Wolverine and other JasperFx libraries. Please check our Support Plans for more details.

Working with Form Data 3.13

Wolverine will allow you to bind HTTP form data to a model type that is decorated with the [FromForm] attribute from ASP.Net Core.

Similar to the above usuage of [FromQuery] Wolverine also supports form parameters as input either directly as method parameters like shown here:

cs
[WolverinePost("/form/string")]
public static string UsingForm([FromForm]string name) // name is from form data
{
    return name.IsEmpty() ? "Name is missing" : $"Name is {name}";
}

snippet source | anchor

And the corresponding test:

cs
[Fact]
public async Task use_string_form_hit()
{
    var body = await Scenario(x =>
    {
        x.Post
            .FormData(new Dictionary<string,string>{
                ["name"] = "Magic"
            })
            .ToUrl("/form/string");
        x.Header("content-type").SingleValueShouldEqual("text/plain");
    });

    body.ReadAsText().ShouldBe("Name is Magic");
}

[Fact]
public async Task use_string_form_miss()
{
    var body = await Scenario(x =>
    {
        x.Post
            .FormData([])
            .ToUrl("/form/string");
        x.Header("content-type").SingleValueShouldEqual("text/plain");
    });

    body.ReadAsText().ShouldBe("Name is missing");
}

[Fact]
public async Task use_decimal_form_hit()
 {
    var body = await Scenario(x =>
    {
        x.WithRequestHeader("Accept-Language", "fr-FR");
        x.Post
            .FormData(new Dictionary<string,string> (){
                {"Amount", "42.1"}
            })
            .ToUrl("/form/decimal");
        x.Header("content-type").SingleValueShouldEqual("text/plain");
    });

    body.ReadAsText().ShouldBe("Amount is 42.1");
}

snippet source | anchor

You can also use the FromForm attribute on a complex type, Wolverine will then attempt to bind all public properties or all parameters from the single default constructor with Form values:

cs
[WolverinePost("/api/fromformbigquery")]
public static BigQuery Post([FromForm] BigQuery query) => query;

snippet source | anchor

Individual properties on the class can be aliased using [FromForm(Name = "aliased")]

Released under the MIT License.