Saturday, July 9, 2016

Avoid querystring in Sitecore MVC using Route Redirect Approach

Use Case : Keep Url clean without any querystring parameter. No additional encoding of url string or tampering by user.




Note: This is not something related to Post Redirect Get Pattern in MVC
http://www.asp.net/mvc/overview/security/preventing-open-redirection-attacks
https://en.wikipedia.org/wiki/Post/Redirect/Get


The sitecore web page contains a list of product and click on product item redirect to product detail page without querystring identifier.


Solution:


Idea is to set session at the interim between href event called and destination item page.


In sitecore there will be controller rendering which is loaded as per sitecore item path url. In this controller we can have navigate method without view actionresult instead we return redirect as url. This navigate action is not control by sitecore item in fact is independent controller action which can be called outside sitecore controller rendering.





public partial class ProductController : RenderingBaseController
{

  public virtual ActionResult Navigate(int id)
        {
            _session.Set("Product", id);
             return Redirect("/product/Detail");
        }
}

Route Registration in sitecore solution

public partial class ProductController : RenderingBaseController
{

  public class MyAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "MyArea";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "myArea_default",
                "myArea/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new { controller = new RegexRouteConstraint("[^api]")  },
                new string[] { "Sitecore.MVC.Areas.MyArea.Controllers" }
            );
        }
    }
}
}

No comments :