Reputation: 19664
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 therefore 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!
Upvotes: 2
Views: 1217
Reputation: 1038770
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.
Upvotes: 3
Reputation: 9799
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()
Upvotes: 1