首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否可以从.net核心中的中间件重定向请求

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

Stack Overflow用户
提问于 2017-04-25 18:00:07
回答 2查看 19.5K关注 0票数 17

我试图实现的是:当有人访问:smartphone.webshop.nl/home/index时,我希望将其从中间件重定向到:webshop.nl/smartphone/home/index

我之所以这样做,是因为我想创建一个通用的控制器,它基于sub-domein从数据库中获取数据。所以我需要所有的调用都转到同一个控制器。

这就是我现在的中间件:

代码语言:javascript
运行
复制
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核心的新手,所以请在你的回答中明确一点。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-25 21:06:33

这就是所谓的网址重写,ASP.NET核心已经为此提供了special middleware (在Microsoft.AspNetCore.Rewrite包中)

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

如果没有-您可以使用check source code并编写您自己的代码。

票数 7
EN

Stack Overflow用户

发布于 2020-06-22 17:17:23

代码语言:javascript
运行
复制
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>();
        }
    }
}
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43607499

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档