Restructure Saxonite workspace and upgrade to .NET 10

This commit is contained in:
2026-10-16 18:20:11 +01:00
parent 2c3fb146ab
commit bfd5202649
1996 changed files with 1997 additions and 1179 deletions
@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
namespace Saxonite.Net.Core.Web.Base.Middleware
{
//=======================================================================
// Authentication handler required to allow actions to issue Forbid() responses.
// Ref. https://stackoverflow.com/questions/54578426/why-do-i-need-to-set-a-defaultforbidscheme/54587054#54587054
//=======================================================================
public class SaxAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
//-------------------------------------------------------------------
// Data members.
//-------------------------------------------------------------------
public SaxAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) :
base(options, logger, encoder, clock)
{
}
//-------------------------------------------------------------------
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return base.HandleForbiddenAsync(properties);
}
//-------------------------------------------------------------------
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// NoOp task to avoid compiler warning.
await Task.CompletedTask;
Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return AuthenticateResult.NoResult();
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using System;
using System.Collections.Generic;
using System.Text;
namespace Saxonite.Net.Core.Web.Base.Middleware
{
//=======================================================================
/// <summary>
/// Force blank form values to be populated to the model as empty strings rather than null values.
/// </summary>
public class SaxMetadataProvider : IMetadataDetailsProvider, IDisplayMetadataProvider
{
public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
{
if (context.Key.MetadataKind == ModelMetadataKind.Property)
{
context.DisplayMetadata.ConvertEmptyStringToNull = false;
}
}
}
//=======================================================================
}
@@ -0,0 +1,116 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Utils;
using Saxonite.Net.Core.Web.Base.App;
using Saxonite.Net.Standard.Base.App;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using static Saxonite.Net.Standard.Base.App.Sax.Config.Security;
// Ignore obsolete warning on ComplexTypeModelBinder.
#pragma warning disable 0618
namespace Saxonite.Net.Core.Web.Base.Middleware
{
//=======================================================================
/// <summary>
/// Maps a browser request to a data object. Default class provides a base implementation of a model binder.
/// <para>Overridden to trim whitespace from input values.</para>
/// </summary>
public class SaxModelBinder : ComplexTypeModelBinder
{
//-------------------------------------------------------------------
// Construction.
public SaxModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) :
base(propertyBinders, loggerFactory)
{
}
//-------------------------------------------------------------------
/// <summary>
/// Creates the model with one (or more) injected service parameters.
/// </summary>
protected override object CreateModel(ModelBindingContext bindingContext)
{
var services = bindingContext.HttpContext.RequestServices;
var modelType = bindingContext.ModelType;
var ctors = modelType.GetConstructors();
foreach (var ctor in ctors)
{
var paramTypes = ctor.GetParameters().Select(p => p.ParameterType).ToList();
var parameters = paramTypes.Select(p => services.GetService(p)).ToArray();
if (parameters.All(p => p != null))
{
var model = ctor.Invoke(parameters);
return model;
}
}
return null;
}
//-------------------------------------------------------------------
/// <summary>
/// Intercept String properties and trim whitespace.
/// </summary>
protected override void SetProperty(ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result)
{
//if (SaxSystem.DebugMode) Logger.Debug(fn + " Form property " + modelName + ": '" + result.Model.ToString() + ".");
object originalValue = result.Model;
// Anything that looks like a password will be left as is.
bool password = modelName.ContainsCI("Password");
// Exclude properties that retain leading/trailing whitespace.
if (result.Model is string)
{
if (!password)
{
string value = result.Model as string;
// Trim leading and trailing whitespace.
value = StringUtil.TrimAll(value);
// Check for multi-line.
if (value.Contains('\n'))
{
// Simplify line delimiters.
value = Regex.Replace(value, "\\r\\n", "\n");
// Remove white space in front of newlines.
value = Regex.Replace(value, "\\s+\\n", "\n");
// Remove multiple newlines.
value = Regex.Replace(value, "\\n+", "\n");
}
// Email addresses must be lowercase to ensure match to encrypted data.
if (modelName.EqualsCI("EmailAddress") || modelName.EqualsCI("AccountEmailAddress"))
value = value.ToLower();
// Uppercase selected values.
if (modelName.EqualsCI("Postcode") || modelName.EqualsCI("AccountPostcode") || modelName.EqualsCI("RegisteredAddressPostcode"))
value = value.ToUpper();
// Assign resulting value.
result = ModelBindingResult.Success(value);
}
}
// Log property details.
if (SaxSystem.DebugMode &&
// Ignore blank values.
result.Model != null && !StringUtil.IsBlank(result.Model.ToString()) &&
// Ignore passwords.
!password &&
// Ignore items that correspond with objects in the model rather than values.
!result.Model.ToString().Equals(result.Model.GetType().FullName) &&
// Ignore form files.
!result.Model.ToString().ContainsCI("Microsoft.AspNetCore.Http.IFormFile"))
SaLogger.Debug(SysUtil.Fn + " Form property " + modelName + ": '" + result.Model.ToString() + "'." + (originalValue != null && !originalValue.Equals(result.Model) ? " Original value: '" + originalValue.ToString() + "'" : ""));
base.SetProperty(bindingContext, modelName, propertyMetadata, result);
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Saxonite.Net.Core.Web.Base.Middleware
{
//=======================================================================
/// <summary>
/// Maps a browser request to a data object. Default class provides a base implementation of a model binder.
/// <para>Overridden to trim whitespace from input values.</para>
/// </summary>
public class SaxModelBinderProvider : IModelBinderProvider
{
//-------------------------------------------------------------------
// Data members.
//-------------------------------------------------------------------
// Construction.
public SaxModelBinderProvider()
{
}
//-------------------------------------------------------------------
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
{
var propertyBinders = context.Metadata.Properties.ToDictionary(property => property, context.CreateBinder);
ILoggerFactory loggerFactory = (ILoggerFactory)context.Services.GetService(typeof(ILoggerFactory));
return new SaxModelBinder(propertyBinders, loggerFactory);
}
// Default - return null so that default binding provider is used.
return null;
}
}
//=======================================================================
}
@@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Utils;
using Saxonite.Net.Standard.Base.App;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Saxonite.Net.Core.Web.Base.Middleware
{
//=======================================================================
/// <summary>
/// Extend IApplicationBuilder class to use the anit-forgery token validation middleware.
/// </summary>
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseAntiforgeryTokens(this IApplicationBuilder app)
{
return app.UseMiddleware<ValidateAntiForgeryTokenMiddleware>();
}
}
//=======================================================================
/// <summary>
/// Ensure relevant actions validate the anti-forgery token, eg. post requests.
/// </summary>
public class ValidateAntiForgeryTokenMiddleware
{
private readonly RequestDelegate _next;
private readonly IAntiforgery _antiforgery;
public ValidateAntiForgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiforgery)
{
_next = next;
_antiforgery = antiforgery;
}
public async Task Invoke(HttpContext context)
{
String fn = GetType().Name + ".Invoke";
// Log action.
//String rawTarget = context.Features.Get<IHttpRequestFeature>().RawTarget;
if (SaxSystem.DebugMode) SaLogger.Trace(fn + " Action: '" + Regex.Replace(context.Request.Path.ToString(), "^/", "") + "'. Method: " + context.Request.Method);
// Intercept POST requests and apply anti-forgery test.
if (HttpMethods.IsPost(context.Request.Method))
{
await _antiforgery.ValidateRequestAsync(context);
}
try
{
await _next(context);
}
catch (Exception exc)
{
SaLogger.Warn(fn + " " + ExceptionUtil.GetLogMessage(exc));
throw;
}
}
}
//=======================================================================
}