[英]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
我想要实现的是:当有人访问:
smartphone.webshop.nl/home/index
我想将它从中间件重定向到: 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
.我想这样做是因为我想创建一个通用控制器,它基于
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?我如何重定向以及我的
controller/mvc
配置应该如何?
I'm pretty new to .net core so please be clear in your answers.我对 .net core 还很陌生,所以请在你的答案中说清楚。 Thank you.
谢谢你。
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>();
}
}
}
That's called URL Rewriting and ASP.NET Core already have special middleware for that (in package Microsoft.AspNetCore.Rewrite
)这就是所谓的 URL 重写,ASP.NET Core 已经为此提供了特殊的中间件(在
Microsoft.AspNetCore.Rewrite
包中)
Check docs, may be you may use it "as is".检查文档,也许您可以“按原样”使用它。
If not - you can check source code and write your own.如果没有 - 您可以检查源代码并编写自己的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.