11

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.

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

5 Comments

'System.Web.Http.Routing.UrlHelper' does not contain a definition for 'Action' and no extension method 'Action' accepting a first argument of type 'System.Web.Http.Routing.UrlHelper' could be found (are you missing a using directive or an assembly reference?)
im a missing some reference ?
The action you want to generate absolute Url to, is it WebApi method or a regular controller action?
no its inside a regular controller. and as i said with this one "http://localhost:1733/controller2/action2" the action works, i just dont want to hardcode my action
Important bit here is the Url.Link. Url.Route generates relative urls.
14

Another, perhaps simpler answer, is to create an instance of UrlHelper in your WebApi class:

var url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
item.Url = url.Action("Doc", "Editor", new {id=1});

Pass in the current request context and you are gold.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.