Skip to content

Instantly share code, notes, and snippets.

@rayonhunte
Created July 11, 2018 15:39
Show Gist options
  • Save rayonhunte/f164f1748db76e69328470ee72766eb7 to your computer and use it in GitHub Desktop.
Save rayonhunte/f164f1748db76e69328470ee72766eb7 to your computer and use it in GitHub Desktop.
real-world-aspnet-web-api-services
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Routing;
namespace DeLoachAero.WebApi
{
public class IsValidAccount : IHttpRouteConstraint
{
public static bool IsValid(string sAccount)
{
return (!String.IsNullOrEmpty(sAccount) &&
sAccount.StartsWith("1234") &&
sAccount.Length > 5);
}
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
IDictionary<string, object> values, HttpRouteDirection routeDirectio)
{
object value;
if(values.TryGetValue(parameterName, out value) && null != value) {
var strAccount = value as string;
if (!String.IsNullOrEmpty(strAccount)) {
if (IsValid(strAccount)) { return true; }
}
}
return false;
}
}
}
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace TestProject3.Controllers
{
[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
[JsonConverter(typeof(StringEnumConverter))]
public enum Widgets
{
Bolt,
Screw,
Nut,
Motor
};
// GET: Products/widget/xxx
[HttpGet, Route("widget/{widget:enum(TestProject3.Controllers.ProductsController+Widgets)}")]
public string GetProductsWithWidget(Widgets widget)
{
return "widget-" + widget.ToString();
}
[HttpGet, Route("accounts/{accountId:validAccount}")]
public string GetValidAccout(string accountId)
{
return "Valid Account-"+ accountId.ToString();
}
}
}
using DeLoachAero.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Routing;
namespace TestProject3
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("enum", typeof(EnumerationConstraint));
constraintResolver.ConstraintMap.Add("validAccount", typeof(IsValidAccount));
config.MapHttpAttributeRoutes(constraintResolver);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment