在ASP.Net Core 2中使用标记帮助程序生成一个很好的URL

时间:2018-01-07 03:18:10

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-tag-helpers

如何使用代码帮助程序生成一个漂亮的URL?

例如:

/Article/FilterByTag?tagId=2

此代码生成类似/Article/FilterByTag/tagId=2

的网址

但我希望/Article/FilterByTag/2getAll(): Observable<AccountsResponse> { return Observable.create(observer => { this.http.get<AccountsResponse>('/accounts') .subscribe((result) => { const manipulatedAccountsResponse = result; // do something with result. manipulatedAccountsResponse.setTotal(100); observer.next(manipulatedAccountsResponse); // call complete if you want to close this stream (like a promise) observer.complete(); }); });

如何使用代码帮助程序生成此URL?

1 个答案:

答案 0 :(得分:2)

[Route("Article/FilterByTag/{tagId}")]

等操作使用属性路由

或者例如

[Route("[controller]")]
public class ArticleController : Controller {

    //...other actions

    [HttpGet]
    [Route("FilterByTag/{tagId}")] // Matches GET Article/FilterByTag/2
    public IActionResult FilterByTag(int tagId) {
        //...

        return View();
    }    
}

这样,当从标记帮助程序引用操作时,生成的链接将映射到操作的路径模板,并返回所需的格式,如Article/FilterByTag/2

  

属性路由需要更多输入来指定路由;传统的默认路由更简洁地处理路由。但是,属性路由允许(并要求)精确控制哪些路径模板应用于每个操作。

参考Routing to Controller Actions