If I call UrlHelper.Link within an API call which has a parameter matching an optional parameter of the API endpoint I'm attempting to obtain an URL for, UrlHelper.Link returns a URL with values from the current request no matter how I try to exclude the optional parameter from the link.
e.g.
[HttpGet]
[Route("api/Test/Stuff/{id}")]
public async Task<IHttpActionResult> GetStuff(int id) // id = 78
{
string link = Url.Link("Mary", new
{
first = "Hello",
second = "World"
});
string link2 = Url.Link("Mary", new
{
first = "Hello",
second = "World",
id = (int?)null
});
string link3 = Url.Link("Mary", new
{
first = "Hello",
second = "World",
id = ""
});
return Ok(new
{
link,
link2,
link3
});
}
[HttpGet]
[Route("api/Test/Another/{first}", Name = "Mary")]
public async Task<IHttpActionResult> AnotherMethod(
[FromUri]string first,
[FromUri]string second = null,
[FromUri]int? id = null)
{
// Stuff
return Ok();
}
GET http://localhost:53172/api/Test/Stuff/8
returns
{
"link": "http://localhost:53172/api/Test/Another/Hello?second=World",
"link2": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8",
"link3": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8"
}
How do you get Url.Link to actually use the values you pass it rather than pull it from the current api request when they are not presented or assigned to null or empty string?
I believe the issue is very similar to ....
UrlHelper.Action includes undesired additional parameters
But this is Web API not MVC, not an action and the answers provided do not seem to yield an obvious solution to this issue.
EDIT: I've updated the code as the original code didn't actually replicate the issue. I've also included a request URL and the response returned, which I've tested. Whilst this code demonstrates the issue, the code I'm trying to find a fix for is not passing an anonymous type to UrlHelper, instead its a class which generates a timestamp and hash and has 4 optional parameters. If there's another solution which doesn't require omitting the optional parameters in the structure passed to UrlHelper I'd like to have it, as it'll save me from making a lot of changes to the code.