UrlHelper.Link returns unwanted parameters

If I call UrlHelper.Link in an API call that has a parameter matching the optional API endpoint parameter, I try to get the URL, UrlHelper.Link returns the URL with the values ​​from the current request no matter how I try to exclude the optional parameter from the link.

eg.

[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, and not extract them from the current api request when they are not presented or are not assigned to a null or empty string?

I believe the problem is very similar to ....

UrlHelper.Action includes unwanted optional parameters

Web API, MVC, , .

EDIT: , . URL- , . , , , UrlHelper, , 4 . , , UrlHelper, , .

+4
1

id .

<null>

public async Task<IHttpActionResult> GetStuff(int id) // id = 78 {
    string myUrl = Url.Link(
        "Mary", 
        new 
        { 
            first = "Hello World"
        });

    //...other code
}

web api 2 id .

[RoutePrefix("api/urlhelper")]
public class UrlHeplerController : ApiController {

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetStuff(int id) {
        string myUrl = Url.Link(
            "Mary",
            new {
                first = "Hello World",
           });
        return Ok(myUrl);
    }

    [HttpGet]
    [Route(Name = "Mary")]
    public IHttpActionResult AnotherMethod(
    [FromUri]string first,
    [FromUri]string second = null,
    [FromUri]int? id = null) {
        // Stuff
        return Ok();
    }
}

client.GetAsync("/api/urlhelper?id=78")

GetStuff

"http://localhost/api/urlhelper?first=Hello%20World"

string myUrl = Url.Link(
    "Mary",
    new {
        first = "Hello World",
        id = ""
    });

id .

+3

Source: https://habr.com/ru/post/1678395/


All Articles