API Get Method not invoking when passing an integer value with empty string in Angular 6

Viewed 1131

In my angular application, I am getting an error when invoking an API method from angular. I have to pass two parameters. First one an integer value and second one string value. it is optional.

Please see the below code snippet (Typescript)

let id:number = 5;
let value: string = "";

this.http.get<string[]>(this.appService.baseUrl + 'api/File/' + id + "/" + value)

In Controller:

[HttpGet("{id:int}/value")]
[ResponseCache(NoStore = true)]
public async Task<IActionResult> Get(int id, string value) { }

Here the Get method is not invoking since the value parameter is empty.

3 Answers

In your example, you're building this URL:

/api/File/5

However, your controller expects the following:

/api/File/5/value

If you want value here to be optional and to be placed into the value parameter (string value), you can adjust your HttpGet attribute, like this:

[HttpGet("{id:int}/{value?}")]

This makes value optional and is a placeholder for whatever gets passed in.

I only have experience with asp.net web api but as far as i am aware having the string value as empty causes the routing to change. Since you don't have a route that takes only an int, your request never reaches your api. What you need to do is overload your Get method and make one that only takes an int.

You entered the type of the variable shareType in the URL, and you are passing empty string for variable shareValue. Remove the :number after the variable shareType and assign a value to the variable shareValue.

Related