Skip to content

Instantly share code, notes, and snippets.

@thojaw
Created December 7, 2017 06:51
Show Gist options
  • Save thojaw/4c585c4a528e30e9ddc0a2edc3b74367 to your computer and use it in GitHub Desktop.
Save thojaw/4c585c4a528e30e9ddc0a2edc3b74367 to your computer and use it in GitHub Desktop.
MVC Reflection based checking of attributes
// Put this in a unit test
var query = Assembly.Load("MyMVCProjectAssemblyName")
.GetTypes()
.Where(x => x.Name.EndsWith("Controller"))
.Where(x => !x.IsAbstract)
.Select(x => new
{
Name = x.Name.Substring(0, x.Name.Length - 10),
Type = x,
Namespace = x.Namespace,
RouteAttribute = x.GetCustomAttribute<RoutePrefixAttribute>()
})
.ToList();
// Now you can perform different tests on the results,
// e.g. you could ensure that each Controller is decorated with Attribute
Assert.IsTrue(query.All(x => RouteAttribute != null));
// Or you could try to validate Route Attribute against Namespace
Assert.IsTrue(query.All(x => x.Namespace.Contains($".{x.RouteAttribute.Prefix}.")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment