Asp.net-Core
如何在 ASP.NET Core 中獲取目前應用程序的相對 URL 以進行登錄重定向
我正在嘗試實現簡單的邏輯,以便使用者在網站上的任何頁面都是使用者在登錄後被重定向回的地方。為此,我似乎需要一種簡單的方法來獲取目前請求的相對 url。
我嘗試在我的 _LoginPartial.cshtml 中使用帶有這樣的連結的完整 url:
<a asp-controller="Login" asp-action="Index" asp-route-returnUrl="@Context.Request.GetEncodedUrl()">Log in</a>但這會導致錯誤:
A URL with an absolute path is considered local if it does not have a host/authority part. URLs using virtual paths ('~/') are also local.似乎應該有一個簡單的內置方法來獲取目前的相對 url。我是否遺漏了什麼或者我需要為此實現自己的擴展方法?我正在使用 RC1
你是說 Context.Request.Path 嗎?
我很快用 HomeController、Index.cshtml 和 Second.cshtml 製作了一個範例項目。Second.cshtml 看起來像:
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" <h1>@ViewBag.Title</h1> <a asp-controller="Home" asp-action="Index" asp-route-returnUrl="@Context.Request.Path">Log in</a>並且錨標記呈現給瀏覽器(使用 Chrome 開發工具測試):
<a href="/?returnUrl=%2FHome%2FSecond">Log in</a>您有 Request.Query 和/或 Request.QueryString 來連接完整的 URL。
您可以在 HttpRequest 類上創建一個擴展方法,例如,如果您願意,可以將 Path 和 QueryString 一起返回。