2017-02-24 31 views
0

我正在使用ASP.NET Core和屬性路由。使用強類型模型時從查詢字符串隱藏屬性

我有這樣的強類型模型

public Command 
{ 
    public int Id { get; set; } 
} 

,因此這個動作

[HttpPost] 
[Route("my route here")] 
public IActionResult Foo(Command command) { ... } 

所以路線是這樣的

.../whatever/foo?id=5 

但我想

.../whatever/foo/5 

我嘗試將屬性更改爲int?但這沒有幫助。

回答

3

您可以用輸入參數定義您的路線。

.../whatever/foo/{id} 

如果要訪問提供的參數,可以將其添加爲方法參數。

public IActionResult Foo(Command command, int id) { ... } 
+0

遺憾的是路由(作爲一個魔法字符串)和強類型模型之間存在路由知識的泄漏/重複。這有效,但我希望有更好的方法。 – grokky

+1

您不需要'int id'參數 - 'DefaultModelBinder'將綁定到'public int Id {get;組; }模型的屬性,因爲名稱匹配 –

+0

@StephenMuecke同意,但答案的第一部分是正確的。 – grokky