我想要实现的目标是: 有人访问时: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);
}
如何重定向以及我的控制器/ mvc配置应该如何?
我对.net核心很新,所以请在答案中说清楚。谢谢。
答案 0 :(得分:6)
这就是所谓的URL重写和ASP.NET核心已经有special middleware(在包Microsoft.AspNetCore.Rewrite
中)
检查文档,可能是“按原样”使用它。
如果没有 - 您可以check source code并自己编写。
答案 1 :(得分:4)
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>();
}
}
}