Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301 Redirect in Asp.Net MVC

I have an Multiculture MVC2 website. Actually my home page can be accessed with the following paths:

http://mydomain.com
http://mydomain.com/
http://mydomain.com/en
http://mydomain.com/en/
http://mydomain.com/en/home
http://mydomain.com/en/home/

What I want is that all the above paths make a 301 redirect to the following:

http://mydomain.com/en

so that I don't have to share pagerank between different urls.

Note that the en string is dynamic and sets the culture for the website.

I'm new in Asp.Net MVC, someone could post some code to do that? Thanks

like image 1000
opaera Avatar asked Dec 02 '25 05:12

opaera


2 Answers

You can create a custom action result. See this thread: http://forums.asp.net/p/1337938/2700733.aspx

like image 103
Jimmy Bosse Avatar answered Dec 03 '25 19:12

Jimmy Bosse


something like this

public class PermanentRedirectResult : ViewResult
{
    public string Url { get; set; }

    public PermanentRedirectResult(string url)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentException("url is null or empty", url);
        this.Url = url;
    }

    public override void ExecuteResult(ControllerContext context)
    {
      if (context == null)
        throw new ArgumentNullException("context");
      context.HttpContext.Response.StatusCode = 301;
      context.HttpContext.Response.RedirectLocation = Url;
      context.HttpContext.Response.End();
    }
}

and call it with this

return new PermanentRedirectResult("/myurl");

like image 20
Rippo Avatar answered Dec 03 '25 17:12

Rippo