Alternative to using Request.URL and Request.URLReferrer to get the current link in MVC?

后端 未结 1 943
不思量自难忘°
不思量自难忘° 2021-01-17 05:28

I was hoping to write a method/property in my BaseController class that would enable any action to get the current URL. If I call localhost/Keyword/Edit/1

相关标签:
1条回答
  • 2021-01-17 05:32

    Create a custom HtmlHelper.Your HtmlHelper's ViewContext property will have just about everything you need about the particular request: HttpContext, RequestContext, RouteData, TempData, ViewData, etc.

    To get the current path of the request, try helper.ViewContext.HttpContext.Request.Path

    You can check the RouteData and obtain the (partial) action and controller, among other route values:

    public static string TestHelper(this HtmlHelper helper)
    {
        var controller = helper.ViewContext.RouteData.Values["controller"].ToString();
        var action = helper.ViewContext.RouteData.Values["action"].ToString();
        return controller + "/" + action;
    }
    

    If called in your Index view , it would return "Home/Index".

    If called in your Partial view , it would return "Home/Partial".

    Hope that helps.

    0 讨论(0)
提交回复
热议问题