开发者

How i can access Virtual Directory in ASP.NET MVC 3 Models?

In Controller it's easy to access the virtual path you need to access like:

Server.MapPath(@"~\App_开发者_JS百科Data\blah\blah") 

This give you access to AppData folder, but if I want to access them in Models, how can I acccess the virtual path in MVC 3?

How can I access my app_data folder in Models of my application ?


If i were you, rather than figuring out how to access the current execution path, I wouldn't break my App layers and pass it as an argument to my model


Your model should not access it - get the controller to provide the data needed.


As Aliostad said, you should have the Controller access it, the model should only hold model data. So here are 2 ways to use the controller to access it.

If virtual folder is in the root of the web application. (If you have to drill down further, just add more parameters to the path combine until you get to your folders location.)

string folderPath = Server.MapPath(System.IO.Path.Combine(Request.ApplicationPath, "VirtualFolderName"));

For a more re-usable solution i created a Extension for the Controller class:

using System.IO;   
using System.Web.Mvc;

    namespace Extensions {
        public static class ControllerExtensions {
            public static string ResolveVirtualFolderPath(this Controller controller, string folder_name) => controller?.HttpContext?.Server?.MapPath(Path.Combine(controller?.HttpContext?.Request?.ApplicationPath, folder_name));                
    }
}

Then in the Controller put the using statement so you can access the extension

using static Extensions.ControllerExtensions;

then you can do this in the controller:

string folderPath = this.ResolveVirtualFolderPath("VirtualFolderNameHere");

You could break the extension down to not use the null check operator "?" and do if null and then handle each situation like the folder does not exist, or maybe access to location is not allowed or whatever else your needs may be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜