Is it possible to redirect request from middleware in .net core

22,634

Solution 1

That's called URL Rewriting and ASP.NET Core already have special middleware for that (in package Microsoft.AspNetCore.Rewrite)

Check docs, may be you may use it "as is".

If not - you can check source code and write your own.

Solution 2

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;

namespace Test.Middleware
{
    public class TestMiddleware
    {
        private readonly RequestDelegate _next;
        public TestMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext httpContext, AppDbContext dataContext, UserManager<User> userManager, IAntiforgery antiforgery)
        {

            // Redirect to login if user is not authenticated. This instruction is neccessary for JS async calls, otherwise everycall will return unauthorized without explaining why
            if (!httpContext.User.Identity.IsAuthenticated && httpContext.Request.Path.Value != "/Account/Login")
            {
                httpContext.Response.Redirect("/Account/Login");
            }

            // Move forward into the pipeline
            await _next(httpContext);
        }
    }
    public static class TestMiddlewareExtensions
    {
        public static IApplicationBuilder UseTestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<TestMiddleware>();
        }
    }
}
Share:
22,634

Related videos on Youtube

apero
Author by

apero

Programmer in training

Updated on June 22, 2020

Comments

  • apero
    apero almost 4 years

    What I'm trying to achieve is this: When someone visits: smartphone.webshop.nl/home/index I want to redirect this from middle ware to: webshop.nl/smartphone/home/index

    I want to do this because I want to create a generic controller which get data from database based on sub-domein. So I need all the calls come to the same controller.

    This is my middleware now:

    public Task Invoke(HttpContext context)
        {
            var subDomain = string.Empty;
    
            var host = context.Request.Host.Host;
    
            if (!string.IsNullOrWhiteSpace(host))
            {
                subDomain = host.Split('.')[0]; // Redirect to this subdomain
            }
    
            return this._next(context);
        }
    

    How can I redirect and how should my controller/mvc config look like?

    I'm pretty new to .net core so please be clear in your answers. Thank you.

    • ColinM
      ColinM about 7 years
      Have you looked at context.Response.Redirect ?
    • apero
      apero about 7 years
      @ColinM Yes I did. That returns a 302 and rewrites the url. But I don't want that. I want the url to be as it is and redirect it only in code.
  • apero
    apero about 7 years
    Thank you very much @Dmitry
  • Adrian Cruz
    Adrian Cruz over 4 years
    Source code link is dead @Dmitry. Can you please update the url.
  • Ilyas Assainov
    Ilyas Assainov over 3 years
    Why don't you show an example on how to do it here?
  • Richard
    Richard about 3 years
    Great solution if you require more control over when to redirect as I required, as opposed to a fixed constant redirect! Thanks!
  • Andrew Boyd
    Andrew Boyd over 2 years
    For this Redirect to execute successfully, you can't allow the code to hit the _next(httpContext);
  • Al-Hanash Moataz
    Al-Hanash Moataz about 2 years
    Simple and Clean +1