是否可以从.net Core中的中间件重定向请求

ape*_*ero 6 .net c# asp.net-mvc asp.net-core

我要实现的目标是:当有人访问时:smartphone.webshop.nl/home/index 我想将其从中间件重定向到:webshop.nl/smartphone/home/index

我要这样做是因为我想创建一个通用控制器,该控制器从上从数据库获取数据sub-domein。因此,我需要所有呼叫都到达同一控制器。

现在这是我的中间件:

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);
    }
Run Code Online (Sandbox Code Playgroud)

我如何重定向以及我的controller/mvc配置应如何显示?

我对.net core来说还很陌生,因此请在回答中明确说明。谢谢。

Iva*_*rta 13

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>();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为了成功执行此重定向,您不能允许代码命中“_next(httpContext);” (8认同)

Dmi*_*try 8

这就是所谓的URL重写,而ASP.NET Core已经为此提供了特殊的中间件(在包中Microsoft.AspNetCore.Rewrite

检查文档,也许您可​​以“按原样”使用它。

如果不是,您可以检查源代码并编写自己的代码

  • 你为什么不在这里展示一个如何做到这一点的例子呢? (10认同)