Last active
September 25, 2017 04:00
-
-
Save tupunco/d4bc4bb745ed02867a6f7bb99dcb8102 to your computer and use it in GitHub Desktop.
ASP.NET Core Default Namespace Area Register Convention, like MVC5 AreaRegistration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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