How to get current virtual path in ASP.NET MVC?

How do you get the current path (url) from an asp.net mvc view?

If there is no way in the view to get it, how can you get it in the controller so that it can be passed to the view?

EDIT

I don't need the protocol and host part of the url.

+3
source share
4 answers

This will return the URL in the view for you:

'<%=Url.RouteUrl(ViewContext.RouteData.Values)%>
+6
source

It depends on which path you need, because there are many alternatives:

// given the url: http://mydomain/approot/my-route/?bar=baz

@Request.Url.PathAndQuery
// value: "/approot/my-route?bar=baz"
@Request.Path
@Request.CurrentExecutionFilePath
// value: "/approot/my-route"
@Request.ApplicationPath
// value: "/approot"
@Request.AppRelativeCurrentExecutionFilePath
// value: "~/my-route"
@Request.AppRelativeCurrentExecutionFilePath.Substring(2)
// value: "my-route"
+4
source

:

<%= Url.RequestContext.HttpContext.Request.CurrentExecutionFilePath %>

@Url.RequestContext.HttpContext.Request.CurrentExecutionFilePath

Razor.

+2

Try:

 <%= Request.Url.AbsolutePath.ToString() %>
+1

Source: https://habr.com/ru/post/1718044/


All Articles