Click here to Skip to main content
16,017,015 members
Home / Discussions / ASP.NET
   

ASP.NET

 
GeneralRe: I think I got it Pin
jkirkerx17-May-23 6:36
professionaljkirkerx17-May-23 6:36 
QuestionHttpUtility.UrlEncode in vb.net Pin
muad AHMED dr3-May-23 20:56
muad AHMED dr3-May-23 20:56 
AnswerRe: HttpUtility.UrlEncode in vb.net Pin
Richard Deeming3-May-23 21:59
mveRichard Deeming3-May-23 21:59 
QuestionVB Linq - Group invoices by store, and include all the invoice items Pin
jkirkerx19-Apr-23 9:20
professionaljkirkerx19-Apr-23 9:20 
AnswerRe: VB Linq - Group invoices by store, and recalculate margin Pin
jkirkerx19-Apr-23 10:00
professionaljkirkerx19-Apr-23 10:00 
QuestionLanguage specific UseRewriter i startup .net core 7 Pin
Tablet510-Apr-23 11:25
Tablet510-Apr-23 11:25 
AnswerRe: Language specific UseRewriter i startup .net core 7 Pin
Richard Deeming10-Apr-23 21:36
mveRichard Deeming10-Apr-23 21:36 
AnswerRe: Language specific UseRewriter i startup .net core 7 Pin
Richard Deeming11-Apr-23 2:20
mveRichard Deeming11-Apr-23 2:20 
The other option would be to use your own middleware. You can see the source of the RewriteMiddleware class on GitHub:
aspnetcore/RewriteMiddleware.cs at b1dcacabec1aeacef72c9aa2909f1cb49993fa73 · strykerin/aspnetcore · GitHub[^]

And the source of the UseRewriter method:
aspnetcore/RewriteBuilderExtensions.cs at b1dcacabec1aeacef72c9aa2909f1cb49993fa73 · strykerin/aspnetcore · GitHub[^]

It shouldn't be too hard to build your own - something like this (untested):
C#
public static class RewriteBuilderExtensions
{
    public static IApplicationBuilder UseMultiRewriter(
        this IApplicationBuilder app, 
        IReadOnlyList<(Func<HttpContext, bool> predicate, RewriteOptions options)> optionsMap)
    {
        ArgumentNullException.ThrowIfNull(app);
        ArgumentNullException.ThrowIfNull(optionsMap);
        return app.UseMiddleware<MultiRewriteMiddleware>(Options.Create(optionsMap));
    }
}

public static partial class MultiRewriteMiddlewareLoggingExtensions
{
    [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "Request did not match any rewrite rule set. Current url is {CurrentUrl}")]
    public static partial void MultiRewriteMiddlewareNoMatchingRules(this ILogger logger, string CurrentUrl);

    [LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = "Request is continuing in applying rules. Current url is {CurrentUrl}")]
    public static partial void MultiRewriteMiddlewareRequestContinueResults(this ILogger logger, string CurrentUrl);

    [LoggerMessage(EventId = 2, Level = LogLevel.Debug, Message = "Request is done processing. Location header '{Location}' with status code '{StatusCode}'.")]
    public static partial void MultiRewriteMiddlewareRequestResponseComplete(this ILogger logger, string Location, int StatusCode);

    [LoggerMessage(EventId = 3, Level = LogLevel.Debug, Message = "Request is done applying rules. Url was rewritten to {RewrittenUrl}")]
    public static partial void MultiRewriteMiddlewareRequestStopRules(this ILogger logger, string RewrittenUrl);
}

public class MultiRewriteMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IReadOnlyList<(Func<HttpContext, bool> predicate, RewriteOptions options)> _optionsMap;
    private readonly IFileProvider _fileProvider;
    private readonly ILogger _logger;
    
    public MultiRewriteMiddleware(
        RequestDelegate next,
        IWebHostEnvironment hostingEnvironment,
        ILoggerFactory loggerFactory,
        IOptions<IReadOnlyList<(Func<HttpContext, bool> predicate, RewriteOptions options)>> optionsMap)
    {
        ArgumentNullException.ThrowIfNull(next);
        ArgumentNullException.ThrowIfNull(optionsMap);

        _next = next;
        _optionsMap = optionsMap.Value;
        _fileProvider = _options.StaticFileProvider ?? hostingEnvironment.WebRootFileProvider;
        _logger = loggerFactory.CreateLogger<MultiRewriteMiddleware>();
    }
    
    public Task Invoke(HttpContext context)
    {
        ArgumentNullException.ThrowIfNull(context);
        
        var options = _optionsMap.Where(m => m.predicate(context)).Select(m => m.options).FirstOrDefault();
        if (options is null)
        {
            _logger.MultiRewriteMiddlewareNoMatchingRules(context.Request.GetEncodedUrl());
            return _next(context);
        }

        RewriteContext rewriteContext = new()
        {
            HttpContext = context,
            StaticFileProvider = _fileProvider,
            Logger = _logger,
            Result = RuleResult.ContinueRules
        };

        foreach (var rule in options.Rules)
        {
            rule.ApplyRule(rewriteContext);
                
            switch (rewriteContext.Result)
            {
                case RuleResult.ContinueRules:
                {
                    _logger.MultiRewriteMiddlewareRequestContinueResults(context.Request.GetEncodedUrl());
                    break;
                }
                case RuleResult.EndResponse:
                {
                    _logger.MultiRewriteMiddlewareRequestResponseComplete(
                        context.Response.Headers[HeaderNames.Location],
                        context.Response.StatusCode);
                    
                    return Task.CompletedTask;
                }
                case RuleResult.SkipRemainingRules:
                {
                    _logger.MultiRewriteMiddlewareRequestStopRules(context.Request.GetEncodedUrl());
                    return _next(context);
                }
                default:
                {
                    throw new ArgumentOutOfRangeException($"Invalid rule termination {rewriteContext.Result}");
                }
            }
        }
        
        return _next(context);
    }
}
C#
RewriteOptions optionsA = new();
optionsA.AddIISUrlRewrite(env.ContentRootFileProvider, "RewritesSiteA.xml");
optionsA.AddRedirectToNonWww();

RewriteOptions optionsB = new();
optionsB.AddIISUrlRewrite(env.ContentRootFileProvider, "RewritesSiteB.xml");
optionsB.AddRedirectToNonWww();

List<(Func<HttpContext, bool> predicate, RewriteOptions options)> optionsMap = new()
{
    (context => context.Request.Host.Host == "siteA.com", optionsA),
    (context => true, optionsB)
};

app.UseMultiRewriter(optionsMap);




"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer

QuestionWeird issue with input form on a simple ASP.NET core web application Pin
Maximilien22-Mar-23 6:49
Maximilien22-Mar-23 6:49 
AnswerRe: Weird issue with input form on a simple ASP.NET core web application Pin
Richard Deeming27-Mar-23 0:42
mveRichard Deeming27-Mar-23 0:42 
GeneralRe: Weird issue with input form on a simple ASP.NET core web application Pin
Maximilien27-Mar-23 6:12
Maximilien27-Mar-23 6:12 
QuestionMessage Removed Pin
19-Mar-23 17:21
samflex19-Mar-23 17:21 
QuestionNeed to Integrate Swipe Machine in my C# Application for billing Pin
Member 159385451-Mar-23 0:58
Member 159385451-Mar-23 0:58 
AnswerRe: Need to Integrate Swipe Machine in my C# Application for billing Pin
Richard Deeming1-Mar-23 1:07
mveRichard Deeming1-Mar-23 1:07 
AnswerRe: Need to Integrate Swipe Machine in my C# Application for billing Pin
jschell20-Mar-23 6:40
jschell20-Mar-23 6:40 
QuestionUsing the WebControlAdapter class with WinForms and ASP.NET 4.5.2 Pin
WhoPinchedMyName28-Feb-23 7:43
WhoPinchedMyName28-Feb-23 7:43 
QuestionI want to show the first lettter of token to be upercase in my code, but it then show the page name and not the token name Pin
hendrikbez23-Feb-23 0:25
hendrikbez23-Feb-23 0:25 
AnswerRe: I want to show the first lettter of token to be upercase in my code, but it then show the page name and not the token name Pin
hendrikbez26-Feb-23 3:24
hendrikbez26-Feb-23 3:24 
Questionhow to auto print label in vb to be in the database Pin
IsdKirti L&tSou20-Feb-23 0:06
IsdKirti L&tSou20-Feb-23 0:06 
AnswerRe: how to auto print label in vb to be in the database Pin
Richard Deeming20-Feb-23 0:45
mveRichard Deeming20-Feb-23 0:45 
QuestionIs it possible to use OData in local mode? Pin
Alex Wright 202217-Feb-23 21:28
Alex Wright 202217-Feb-23 21:28 
QuestionHow to enable nested json result in OData (ASP.NET Core API) Pin
Alex Wright 202214-Feb-23 20:57
Alex Wright 202214-Feb-23 20:57 
AnswerRe: How to enable nested json result in OData (ASP.NET Core API) Pin
Richard Deeming14-Feb-23 22:11
mveRichard Deeming14-Feb-23 22:11 
GeneralRe: How to enable nested json result in OData (ASP.NET Core API) Pin
Alex Wright 202214-Feb-23 22:33
Alex Wright 202214-Feb-23 22:33 
Question(SOLVED) Having problem showing just a section of a page. Pin
samflex16-Jan-23 10:40
samflex16-Jan-23 10:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.