How to correctly canonicalize a URL in an ASP.NET MVC application?

后端 未结 3 866
借酒劲吻你
借酒劲吻你 2021-02-03 11:45

I\'m trying to find a good general purpose way to canonicalize urls in an ASP.NET MVC 2 application. Here\'s what I\'ve come up with so far:

// Using an authoriz         


        
3条回答
  •  故里飘歌
    2021-02-03 12:10

    Below is how I do my canonical URLs in MVC2. I use IIS7 rewrite module v2 to make all my URLs lowercase and also strip trailing slashes so don't need to do it from my code. (Full blog post)

    Add this to the master page in the head section as follows:

    <%=ViewData["CanonicalURL"] %>
    
    

    Create a Filter Attribute (CanonicalURL.cs):

    public class CanonicalURL : ActionFilterAttribute
    {
        public string Url { get; private set; }
    
        public CanonicalURL(string url)
        {
           Url = url;
        }
    
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            string fullyQualifiedUrl = "http://www.example.com" + this.Url;
            filterContext.Controller.ViewData["CanonicalUrl"] = @"";
            base.OnResultExecuting(filterContext);
        }
    }
    

    Call this from your actions:

    [CanonicalURL("Contact-Us")]
    public ActionResult Index()
     {
          ContactFormViewModel contact = new ContactFormViewModel(); 
          return View(contact);
    }
    

    For some other interesting articles on Search Engine Related posts check out Matt Cutts blog

提交回复
热议问题