【问题标题】:Is it possible to redirect request from middleware in .net core是否可以从.net核心中的中间件重定向请求
【发布时间】:2017-04-25 10:00:07
【问题描述】:

我想要实现的是: 有人来访时: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);
    }

如何重定向以及我的controller/mvc 配置应该是什么样子?

我对 .net core 很陌生,所以请在你的答案中明确。谢谢。

【问题讨论】:

  • 你看过context.Response.Redirect吗?
  • @ColinM 是的,我做到了。这将返回 302 并重写 url。但我不想那样。我希望 url 保持原样并仅在代码中重定向它。

标签: c# .net asp.net-mvc asp.net-core


【解决方案1】:
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>();
        }
    }
}

【讨论】:

  • 如果您需要根据我的要求更多地控制何时重定向,而不是固定不变的重定向,这是一个很好的解决方案!谢谢!
  • 为了成功执行这个重定向,你不能让代码命中_next(httpContext);
【解决方案2】:

这称为 URL 重写,ASP.NET Core 已经有 special middleware (在包 Microsoft.AspNetCore.Rewrite 中)

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

如果没有 - 您可以 check source code 并自己编写。

【讨论】:

  • 非常感谢@Dmitry
  • 源代码链接已失效@Dmitry。你能更新一下网址吗?
  • 你为什么不在这里展示一个如何做的例子?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 2015-01-19
  • 2021-08-21
  • 1970-01-01
  • 2017-09-16
相关资源
最近更新 更多