user4383363
user4383363

Reputation:

Why is this HttpRequestMessage's request URI invalid?

I am trying to write an integration test where I test the signup functionality of my application. This is the controller:

[Route("account")]
public class IdentityController : MainController
{
    // ...

    [HttpGet("signup")]
    public IActionResult SignUp()
    {
        return View();
    }

    [HttpPost("signup")]
    public async Task<IActionResult> SignUp(UserSignUpViewModel signUp)
    {
        if (!ModelState.IsValid)
        {

I am following an online training, and according to the video as well as other examples around, this is how it was supposed to be done to be able to test the form submission:

[Fact]
public async Task Identity_CreateUser_ShouldBeSuccessful()
{
    // Arrange
    var initialResponse = await _fixture.Client.GetAsync("/account/signup");
    initialResponse.EnsureSuccessStatusCode();

    var antiForgeryToken = _fixture.GetAntiForgeryToken(await initialResponse.Content.ReadAsStringAsync());

    var postRequest = new HttpRequestMessage(HttpMethod.Post, "/account/signup")
    {
        Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            { "Name", "John Malone Doe" },
            // ...
        }
    }

    // Act
    var response = await _fixture.Client.SendAsync(postRequest);

    // ...

Rider will even auto-complete the path for me, But it will fail with a message saying:

System.InvalidOperationException: An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

I tried passing the full address, "https://localhost:5001/account/signup", and also writing the code this way:

var postRequest = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://localhost:5001/account/signup"),
    Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {

None solved.

Upvotes: 2

Views: 2218

Answers (1)

Brendan R.
Brendan R.

Reputation: 113

It seems the URIs need a trailing slash to be valid

See: Create new URI from Base URI and Relative Path - slash makes a difference?

Rather than https://localhost:5001/account/signup, try https://localhost:5001/account/signup/.

(There is a slash at the end of the second)

I haven’t tested this though.

Upvotes: 0

Related Questions