如果我在調用具有與API端點的可選參數匹配的參數的API調用中調用UrlHelper.Link我試圖獲取URL,UrlHelper.Link返回一個包含值當前請求無論我如何嘗試從鏈接中排除可選參數。UrlHelper.Link返回不需要的參數
例如
[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
回報
{
"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"
}
你怎麼Url.Link實際使用傳遞給它的值,而不是從當前的API請求把它時,不會呈現他們或分配給null或空字符串?
我相信這個問題是非常相似....
UrlHelper.Action includes undesired additional parameters
但這網頁API不MVC,不是一個動作,並提供似乎並沒有產生明顯的解決了這個問題的答案問題。
編輯:我更新了代碼,因爲原始代碼並未真正複製該問題。我還包含了一個請求URL和返回的響應,我已經測試過了。雖然這段代碼演示了這個問題,但我試圖找到修復的代碼並不是將一個匿名類型傳遞給UrlHelper,而是將其生成時間戳和散列並具有4個可選參數的類。如果還有另一個解決方案,不需要在傳遞給UrlHelper的結構中省略可選參數,我希望擁有它,因爲它可以讓我無需對代碼進行大量更改。
同時顯示原始URL和鏈接生成的URL。 – Nkosi
我建議答案是更多的工作。我認爲這會讓很多人錯誤地認爲將任何結構(包括匿名或類類型)傳遞給UrlHelper的屬性賦給一個空或空值的屬性與忽略該值相同。雖然行爲可能實際上是通過設計,但我認爲這是非常不舒服的想法,而不是你期望的 – Mick