0

I am trying to call a method in a webapiController(.net core) from my test

If my request object has an Id as string it does not work ,as an int it does

what Am I doing wrong in my noddy sample?

    [Fact]
    public async Task WhyDoesNotWorkWithIdAsString()
    {
        string thisQueryDoesNotWork = "http://localhost:1111/api/v1/shop/customers?id=1";
        string thisQueryWorksProvidedTheIdIsAnInt = "http://localhost:1111/api/v1/shop/customers/1";
        var response = await client.GetAsync(thisQueryDoesNotWork);
        var response2 = await client.GetAsync(thisQueryWorksProvidedTheIdIsAnInt);

        //omitted asserts
    }


[Route("api/[controller]")]
public class ShopController: Controller
{

    [HttpGet]
    [Route("{id}",Name ="GetCustomerAsync")]
    [ProducesResponseType(typeof(GetCustomerResponse), (int)HttpStatusCode.OK)]
            //more ProducesResponseType omitted
    public async Task<IActionResult> GetCustomerAsync([FromQuery]GetCustomerRequest request)
    {
        //code omitted
    }
}


public class GetCustomerRequest
{
    Required]
    public string Id { get; set; }
    // public int Id { get; set; }   //works with int but not with a string

}

}

Also is below correct

[FromQuery]=use Get only [FromBody]=use Put-Post

is there a link with explanation when to use this parameter binding?

many thanks

1

2 Answers 2

1

In

[Route("{id}",Name ="GetCustomerAsync")]

{id} template parameter is part of the route but in the action parameter is it being requested via [FromQuery], which is why it is not matching.

It is expecting

http://localhost:1111/api/v1/shop/customers/1

But your are sending

http://localhost:1111/api/v1/shop/customers?id=1

which is why the second link works and the first does not.

Reference Routing to Controller Actions

As for the concern about [From*] attributes

[FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding source you want to apply.
...
[FromBody]: Use the configured formatters to bind data from the request body. The formatter is selected based on content type of the request.

Reference Model Binding in ASP.NET Core

Sign up to request clarification or add additional context in comments.

Comments

0

I have found out what the problem is, Name of the httpget or route must match the one you setup in the link

1 Comment

@nkosi I understand that u use [frombody] for put and post but when do u use from query vs from route

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.