2021-11-30 15:35:50 +01:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
2021-12-01 13:03:06 +01:00
|
|
|
using System.Reflection;
|
2021-11-30 15:35:50 +01:00
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace zero.Api.Controllers;
|
|
|
|
|
|
|
|
|
|
public class ZeroApiControllerModelConvention : IControllerModelConvention
|
|
|
|
|
{
|
2021-12-01 13:03:06 +01:00
|
|
|
readonly AttributeRouteModel AppAwareRouteModel;
|
|
|
|
|
|
|
|
|
|
readonly AttributeRouteModel AppUnawareRouteModel;
|
2021-11-30 15:35:50 +01:00
|
|
|
|
|
|
|
|
readonly Type BaseClass = typeof(ZeroApiController);
|
|
|
|
|
|
2021-12-01 13:03:06 +01:00
|
|
|
readonly bool RuntimeIsAppAware = false;
|
|
|
|
|
|
2021-11-30 15:35:50 +01:00
|
|
|
|
|
|
|
|
public ZeroApiControllerModelConvention(string zeroPath, string apiPath = "api", bool isAppAware = false)
|
|
|
|
|
{
|
2021-12-01 13:03:06 +01:00
|
|
|
RuntimeIsAppAware = isAppAware;
|
|
|
|
|
AppAwareRouteModel = BuildRouteModel(zeroPath, apiPath, true);
|
|
|
|
|
AppUnawareRouteModel = BuildRouteModel(zeroPath, apiPath, false);
|
2021-11-30 15:35:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Configure routing model for all backoffice controllers
|
|
|
|
|
/// </summary>
|
2021-12-03 14:45:49 +01:00
|
|
|
public virtual void Apply(ControllerModel controller)
|
2021-11-30 15:35:50 +01:00
|
|
|
{
|
|
|
|
|
bool hasAttributeRouteModels = controller.Selectors.Any(selector => selector.AttributeRouteModel != null);
|
|
|
|
|
|
|
|
|
|
if (controller.ControllerType.IsSubclassOf(BaseClass))
|
|
|
|
|
{
|
2021-12-01 13:03:06 +01:00
|
|
|
bool isAppAware = RuntimeIsAppAware && controller.ControllerType.GetCustomAttribute<ZeroSystemApiAttribute>() == null;
|
|
|
|
|
|
|
|
|
|
controller.Selectors[0].AttributeRouteModel = isAppAware ? AppAwareRouteModel : AppUnawareRouteModel;
|
2021-11-30 15:35:50 +01:00
|
|
|
}
|
|
|
|
|
}
|
2021-12-01 13:03:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
protected AttributeRouteModel BuildRouteModel(string zeroPath, string apiPath, bool appAware = false)
|
|
|
|
|
{
|
|
|
|
|
StringBuilder path = new();
|
|
|
|
|
path.Append(zeroPath.EnsureEndsWith('/'));
|
|
|
|
|
path.Append(apiPath.TrimStart('/').EnsureEndsWith('/'));
|
|
|
|
|
|
|
|
|
|
if (appAware)
|
|
|
|
|
{
|
|
|
|
|
path.Append("{zero_app_slug}/");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
path.Append("[controller]");
|
|
|
|
|
|
|
|
|
|
return new AttributeRouteModel(new RouteAttribute(path.ToString()));
|
|
|
|
|
}
|
2021-11-30 15:35:50 +01:00
|
|
|
}
|