Skip to main content

A complete example on how to implement a ASP.NET Web API Route Constraint.

// --------------------------------------------------------------------------
// Constraints/IdConstraint.cs
// --------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http.Routing;

namespace MyApp.Constraints
{
    public class IdConstraint : IHttpRouteConstraint
    {
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            object value;

            if (!values.TryGetValue(parameterName, out value) || value == null)
            {
                return false;
            }

            try
            {
                return Convert.ToInt32(value) > 0;
            }
            catch
            {
                return false;
            }
        }
    }
}

// --------------------------------------------------------------------------
// Controller/CalendarController.cs
// --------------------------------------------------------------------------

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyApp.Controllers
{
    [RoutePrefix("api/tour")]
    public class CalendarController : ApiController
    {
        private AppDbContext _db = new AppDbContext();

        [Route("{id:identity}")]
        public Tour Get(int id)
        {
            var item = _db.Calendars
                .FirstOrDefault(i => i.CalendarId == id);

            return item;
        }
    }
}

// --------------------------------------------------------------------------
// App_Start/Startup.cs (Service Registration)
// --------------------------------------------------------------------------

using System;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Routing;
using MyApp.Config;
using MyApp.Constraints;
using MyApp.ExceptionHandlers;
using MyApp.Filters;
using MyApp.Loggers;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Owin;

[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
    public class Startup
    {
        public static HttpConfiguration HttpConfiguration { get; set; } = new HttpConfiguration();

        public void Configuration(IAppBuilder app)
        {
            var config = Startup.HttpConfiguration;

            // var json = config.Formatters.JsonFormatter.SerializerSettings;
            // json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            ConfigureWebApi(app, config);
        }

        private static void ConfigureWebApi(IAppBuilder app, HttpConfiguration config)
        {
            var constraintResolver = new DefaultInlineConstraintResolver();
            constraintResolver.ConstraintMap.Add("identity", typeof(IdConstraint));
            config.MapHttpAttributeRoutes(constraintResolver);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            app.UseWebApi(config);
        }
    }
}