0

I am trying to redirect to a page in MVC website so I have the following code in my controller:

return Redirect("/test");

I am running my site locally through IIS on a domain of test.local and when I hit this controller I would expect to go off to http://test.local/test but instead, for some reason, it is redirecting me to http://localhost/test

Does anyone know how I can make it stay on the same domain without having to put the domain name into the redirect or do I have to include the domain name as well?

Please note as well that I am unable to use RedirectToRoute or RedirectToAction as the url is a separate application (under the same domain as the current site)

Pete
  • 57,112
  • 28
  • 117
  • 166

1 Answers1

0

I have created a extension method that provides to redirect on the same domain. Maybe this helps

public static class ControllerExtension
{
    public static string FullyQualifiedApplicationPath
    {
        get
        {
            //Return variable declaration
            var appPath = string.Empty;

            //Getting the current context of HTTP request
            var context = HttpContext.Current;

            //Checking the current context content
            if (context != null)
            {
                //Formatting the fully qualified website url/name
                appPath = string.Format("{0}://{1}{2}{3}",
                                        context.Request.Url.Scheme,
                                        context.Request.Url.Host,
                                        context.Request.Url.Port == 80
                                            ? string.Empty
                                            : ":" + context.Request.Url.Port,
                                        context.Request.ApplicationPath);
            }

            if (!appPath.EndsWith("/"))
                appPath += "/";

            return appPath;
        }
    }

    public static RedirectResult RedirectSameDomain(this Controller controller, string url)
    {
        return new RedirectResult(FullyQualifiedApplicationPath + url);
    }
}

You can use it like this

return this.RedirectSameDomain("/test");

Thanks to SO User Brian Hasden for FullyQualifiedApplicationPath and his answer on How can I get the root domain URI in ASP.NET?

Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202