Can I limit the page number using MVC routing?

My urls look like this:

/category/page-#

/tag/product/page-#

......

      

Can I use MVC routing to limit the page number? I want to do the following:

routes.MapRoute(
  name: "limitPaging",
  url: "*/page-{pageNumber}",
  defaults: new { controller = "Error", action = "P404", }, 
            new { pageNumber = @"\d+" }, 
            new { pageNumber > 200 }
);

      

thank

+3


source to share


2 answers


You can create your own route constraint (class that implements IRouteConstraint

)

public class LessThanPage : IRouteConstraint
{
  private int _maxPage;

  public LessThanPage(int maxPage)
  {
    _maxPage = maxPage;
  }

  public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
  {
    return Convert.ToInt32(values[parameterName].ToString()) <= _maxPage;
  }
}

routes.MapRoute(
  name: "limitPaging",
  url: "*/page-{pageNumber}",
  defaults: new { controller = "Error", action = "P404", }, 
  constraints: new { pageNumber > new LessThanPage(200) }
);

      



You can also use this method to validate that this parameter is a number and therefore exclude the regex constraint

+1


source


Following @Stephen Muecke's answer, I did it this way:

public class LessThanPage : IRouteConstraint
    {
        private int _maxPage;

        public LessThanPage(int maxPage)
        {
            _maxPage = maxPage;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return httpContext.Request.RawUrl.ToLower().Contains("/page-") && GetPageNumberFromURL(httpContext.Request.RawUrl.ToLower()) > _maxPage;
        }

        private int GetPageNumberFromURL(string url)
        {
            var pageNumber = 1;
            var iIndexOfPage = url.IndexOf("/page-");
            var iIndexOfHash = url.IndexOf('#') > -1 ? url.IndexOf('#') : url.Length;
            if (iIndexOfPage >= 0 && iIndexOfHash - iIndexOfPage > 0)
                pageNumber = int.Parse(url.Substring(iIndexOfPage, iIndexOfHash - iIndexOfPage).Split('-')[1]);

            return pageNumber;
        }
    }

      



Routing syntax:

routes.MapRoute(
              name: "limitPaging",
              url: "{*url}",
              defaults: new { controller = "Error", action = "P404" },
              constraints: new { pageNumber = new LessThanPage(200), }
            );

      

+1


source







All Articles