'Simulate Form Content in Test Case

I have an ASP page with a simple form:

<form method="post" enctype="multipart/form-data">
    <input asp-for="@Model.Answer" type="text" id="answer">
    <button type="submit" formaction="/Result" formmethod="post" >Answer</button>
</form>

Which works to fill the model of the Result page:

public class ResultModel : PageModel
{
    public void OnPost(string answer)
    {
        // answer is the value of the input
    }
}

Now I want to call the Result page inside a test case:

var factory = new WebApplicationFactory();
var client = factory.CreateClient();
var response = await client.PostAsync("Result", postContent);

I'm struggling to find the right postContent that simulates the answer input field. I tried:

var postContent = new FormUrlEncodedContent (new KeyValuePair<string, string>[] { new("answer", "bla") });


var postContent = new MultipartContent ("form-data");
postContent.Add(new FormUrlEncodedContent (new KeyValuePair<string, string>[] { new("answer", "bla") }));


var postContent = new StringContent("{ \"answer\" = \"incorrect\" }",  Encoding.UTF8, "application/json");


var postContent = new ByteArrayContent(Encoding.ASCII.GetBytes("answer=abc"));


var postContent = new MultipartFormDataContent();
postContent.Add(new StringContent("test"), "Answer");

And also directly using curl:

> curl -i -d "Answer=value" -H "Content-Type: multipart/form-data" -X POST https://localhost:7291/quiz/Result --insecure
HTTP/1.1 400 Bad Request
Content-Length: 0
Date: Sun, 20 Mar 2022 21:00:41 GMT
Server: Kestrel

But I always get a return value of 400 - BadRequest without any information on what was bad. If I use client.GetAsync() I get 404 - NotFound, which is expected. If I remove the value of PageModel.OnPost(), I still get BadRequest, so it's maybe not the parameter which is the problem? Maybe it's the content type, but I monitored the traffic in the browser, and the content type is "multipart/form-data" which I'm trying to reproduce.

How do I make this work?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source