ASP.NET MVC3 Root path to virtual path in controller or model

This sounds like a pretty simple question, but cannot find the answer to my life. How to convert root relative url ( ~/my/path ) to a virtual path ( /mywebsite/my/path ) in the controller and / or model?

To view it, just make a call to @Url.Content("~/my/path/") . And getting the physical path in the controller is just as easy using Server.MapPath("~/my/path") . But I can’t figure out how to get the virtual path in the controller.

My main problem is that I have the root path of the image that I will pass to the JSON object that will be returned. In most cases, this will be read by javascript and placed on the page somewhere, and I cannot use @Url.Content in my javascript code. Also, in some cases, this JSON object will be used by an external application that will not understand what ~ means.

+4
source share
1 answer

In the controller, you can use the Url property:

 public ActionResult Foo() { string url = Url.Content("~/my/path"); ... } 

You are not doing anything in the model. The model should not know anything about generating URLs. This is simply not his responsibility. If he needs to work with a URL, that URL must be passed to him by the layers of your application that handle the URLs (which are the layers that have access to the HttpContext).

+6
source

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


All Articles