asp.net mvc - Generating absolute url to action from within Api controller -


im working asp.net mvc4 , have in 'controller1' 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 set uri "http://localhost:1733/controller2/action2" action works fine, never uri set "controller2/action2" or "/controller2/action2" or "~/controller2/action2".

how can write action without hardcoding uri ?

thank you.

use:

string uri = url.action("action2", "controller2", new {}, request.url.scheme); 

update:

since you're using api controller , need generate url regular controller, you're gonna have use:

string uri = this.url.link("default", new { controller = "controller2", action = "action2" }); 

where default name of route defined in registered routes collection, or if created specific route action, use it's name , new{} 2nd parameter.

for mvc version 4, check registered routes @ ~/app_start/routesconfig.cs. mvc version 3, check registerroutes method in global.asax.


Comments