Skip to content

Instantly share code, notes, and snippets.

@tupunco
Last active September 25, 2017 04:00
Show Gist options
  • Save tupunco/d4bc4bb745ed02867a6f7bb99dcb8102 to your computer and use it in GitHub Desktop.
Save tupunco/d4bc4bb745ed02867a6f7bb99dcb8102 to your computer and use it in GitHub Desktop.
ASP.NET Core Default Namespace Area Register Convention, like MVC5 AreaRegistration
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
namespace TupMvcCore.Conventions
{
/// <summary>
/// Default Area Load ControllerModelConvention
/// </summary>
public class DefaultAreaConvention : IControllerModelConvention
{
private static readonly string s_Area_RouteKey = "area";
private static readonly Regex s_Area_Reg = new Regex(@"\.Areas\.(?<area>[\w\d]+)\.Controllers\.[\w\d]+Controller$", RegexOptions.IgnoreCase);
public void Apply(ControllerModel controller)
{
var rValues = controller.RouteValues;
if (rValues.ContainsKey(s_Area_RouteKey))
return;
var cfName = controller.ControllerType.FullName;
var areaMatch = s_Area_Reg.Match(cfName);
if (!areaMatch.Success)
return;
var areaName = areaMatch.Groups["area"].Value;
rValues.Add(s_Area_RouteKey, areaName);
}
}
}
public class Startup
{
//.....
public void ConfigureServices(IServiceCollection services)
{
//.....
services.AddMvc(options =>
{
//.....
options.Conventions.Add(new DefaultAreaConvention());
//.....
});
//.....
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment