Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating absolute url to action from within Api controller

Tags:

asp.net-mvc

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.

like image 279
dafriskymonkey Avatar asked Jul 19 '13 07:07

dafriskymonkey


People also ask

How do you give a controller a URL?

If you just want to get the path to a certain action, use UrlHelper : UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u.


1 Answers

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.

like image 196
haim770 Avatar answered Sep 17 '22 12:09

haim770