im working with asp.net mvc4 and i have in 'controller1' this action :
[HttpGet]
public async Task<string> Action1()
{
try
{
HttpClient cl = new HttpClient();
string uri = "controller2/action2";
HttpResponseMessage response = await cl.GetAsync(uri);
response.EnsureSuccessStatusCode();
return response.ToString();
}
catch
{
return null;
}
}
when i set uri to "http://localhost:1733/controller2/action2"
the action works fine, BUT never with uri set to "controller2/action2" or "/controller2/action2" or "~/controller2/action2".
how can i write this action without hardcoding the uri ?
Thank you.
If you just want to get the path to a certain action, use UrlHelper : UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u.
Use:
string uri = Url.Action("Action2", "Controller2", new {}, Request.Url.Scheme);
Update:
Since you're using an API controller and need to generate a Url to a regular controller, you're gonna have to use:
string uri = this.Url.Link("Default", new { controller = "Controller2", action = "Action2" });
Where Default
is the name of the route
defined in your registered routes collection, or if you already created a specific route for this action, use it's name and new{}
as the 2nd parameter.
For MVC version 4, check your registered routes at ~/App_Start/RoutesConfig.cs
. for MVC version 3, check your RegisterRoutes
method in your Global.asax
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With