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.
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.
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 ).
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.
Redirect(String) Redirects a request to a new URL and specifies the new URL.
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>();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With