brian4342
brian4342

Reputation: 1253

How to redirect to an MVC page

I have currently got a MVC application that redirects to another website:

public ActionResult Index()
    {
        //create instance of class to get info
        FreeAgentInfo info = new FreeAgentInfo();

        //Create Url and redirect
        string url = string.Format(@"{0}/v{1}/approve_app?&redirect_uri={3}&response_type=code&client_id={2}", info.BaseUrl, info.Version, info.ApiKey, info.Callback);
        return Redirect(url);
    }

This will send the application to another website but when its finsihed it needs to return to the MVC app. This is done by providing a callback url for it to redirect to. The callback needs to a link to a page on my MVC app

For example I also have this action:

public ActionResult Invoices()
    {
        return View();
    }

Its location is "~/Views/Home/Invoices.cshtml" and its running off the localhost

What should I use as the callback url to get it to return to this page?

Upvotes: 0

Views: 1548

Answers (3)

Waheed Rafiq
Waheed Rafiq

Reputation: 482

Just to emphasise RedirectToAction() tells MVC to redirect to specified action instead of rendering HTML, it acts like a Response.Redirect() in ASP.NET WebForm.

public ActionResult Index()
{
  return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
   ViewBag.Message = "Hello Word";
   //Like Server.Transfer() in Asp.Net WebForm
   return View("MyIndex");
}

public ActionResult MyIndex()
{
  ViewBag.Msg = ViewBag.Message; // Assigned value : "Hello World"
  return View("MyIndex");
 }

Hope this clarifies the situation.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You could use the Url helper to generate an absolute url for the callback that you would pass to the external website:

string callback = Url.Action("Invoices", "MyController", null, Request.Url.Scheme);

and then pass this callback:

string url = string.Format(
    @"{0}/v{1}/approve_app?&redirect_uri={3}&response_type=code&client_id={2}", 
    info.BaseUrl, 
    info.Version, 
    info.ApiKey, 
    callback
);
return Redirect(url);

By using the Url helper it is guaranteed that this will always generate a valid url to your controller action no matter what routes you have configured. Also if you change your routes one day, you don't need to remember that you had some custom code calculating this callback when calling the external website.

So never hardcode urls in an ASP.NET MVC application. Always use url helpers when dealing with them.

Upvotes: 4

brian4342
brian4342

Reputation: 1253

Solved it, I was adding "/Views/" to the url.

"http://localhost:52006/Home/Invoices"

Thats the solution :)

Upvotes: 1

Related Questions