开发者

IIS ApplicationName at runtime ASP.net

I am constructing a URL at runtime in a ASP.NET MVC application. What is the best way to do this?

 url = string.Format("/controller/action/{0}/{1}/{2}/{3}/{4}", request.Id,
                                           builds.Release, builds.Localization.Value, builds.Label, SessionId);

The URL is ultimately used to make an AJAX call back to a controller action. The problem is that in my deployment environment this application is not the root and th开发者_如何学Pythonerefore the URL is not valid.

{host}\url <-- this is what I have. {host}{applicationname}\url <-- this is what I need.

So I was going to resolve the application name at runtime and use it to construct the url. How can I get just the applicationname? Is this the best way?

Thanks!


The best way is to use the URL helper Action method:

Url.Action("SomeAction", "SomeController", new { 
    id = request.Id, 
    release = builds.Release, 
    localization = builds.Localization.Value, 
    label = builds.Label, 
    sessionId = SessionId 
}); 

This obviously implies that you have the correct route set (taking id, release, localization, label and sessionId tokens):

routes.MapRoute(
    "MyRoute",
    "{controller}/{action}/{id}/{release}/{localization}/{label}/{sessionId}",
    new { controller = "SomeController", action = "SomeAction" }
);

Remark: never use string concatenations and/or string.Format when dealing with urls if you don't want to have problems with url encodings, etc...

Remark 2: An instance of the UrlHelper is available in each controller action as Url property of the controller, in each view, and in each helper.


You should include Request.ApplicationPath as the firt part of your url.

url = string.Format("{0}controller/action/{1}/{2}/{3}/{4}/{5}", Request.ApplicationPath, request.Id,
                                           builds.Release, builds.Localization.Value, builds.Label, SessionId);

You may also want to take a look at the VirtualPathUtility class. Specifically

VirtualPathUtility.ToAbsolute()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜