Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 318
apero Avatar asked Apr 25 '17 10:04

apero


People also ask

How do I redirect in middleware NET Core?

In a browser with developer tools enabled, make a request to the sample app with the path /redirect-rule/1234/5678 . The regular expression matches the request path on redirect-rule/(. *) , and the path is replaced with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 - Found status code.

What is difference between middleware and filters in .NET Core?

A middleware can run for all requests while filters will only run for requests that reach the EndpointMiddleware and execute an action from an API Controller or a Razor Page. Filters have access to MVC components (eg: ModelState or IActionResults ).

What is middleware in .NET Core and how is it injected in the request pipeline?

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.

Which method redirects a request to a new URL?

Redirect(String) Redirects a request to a new URL and specifies the new URL.


1 Answers

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>();
        }
    }
}
like image 118
Ivan Porta Avatar answered Oct 21 '22 11:10

Ivan Porta