Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Last active August 29, 2015 13:57
Show Gist options
  • Save hagbarddenstore/9887822 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/9887822 to your computer and use it in GitHub Desktop.
An IRouteConstraint for ASP.NET MVC that validates a route data value to be a valid GUID.
namespace Hagbarddenstore.Mvc
{
using System;
using System.Web;
using System.Web.Routing;
/// <summary>
/// Defines the GuidConstraint type.
/// </summary>
public class GuidConstraint : IRouteConstraint
{
/// <summary>
/// Determines whether the URL parameter contains a valid value for this constraint.
/// </summary>
/// <param name="httpContext">
/// An object that encapsulates information about the HTTP request.
/// </param>
/// <param name="route">
/// The object that this constraint belongs to.
/// </param>
/// <param name="parameterName">
/// The name of the parameter that is being checked.
/// </param>
/// <param name="values">
/// An object that contains the parameters for the URL.
/// </param>
/// <param name="routeDirection">
/// An object that indicates whether the constraint check is being performed when an incoming
/// request is being handled or when a URL is being generated.
/// </param>
/// <returns>
/// <c>true</c> if the URL parameter contains a valid value; otherwise, <c>false</c>.
/// </returns>
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
object value;
if (values.TryGetValue(parameterName, out value))
{
if (value is Guid)
{
return true;
}
if (value is string)
{
Guid guidValue;
return Guid.TryParse(value as string, out guidValue) && !Guid.Empty.Equals(guidValue);
}
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment