Asp.net core 如何将租户/组织id添加到每个URL并在控制器中读取
我正在编写一个ASP.NET核心web应用程序。在我的应用程序中,用户可以是一个或多个组织的成员(此信息存储在数据库中)。我想让用户可以选择整个应用程序应该运行的组织上下文。这个上下文应该传递给每个控制器,这样我就可以进行适当的检查并只返回所选组织的数据 换句话说,我希望达到用户可以通过以下方式访问应用程序的状态: app.mydomain.com/org1/controller/action/id并使用下拉菜单,他们应该能够切换到org2并访问app.mydomain/org2/controller/action/id 在这两种情况下,我都需要能够读取控制器中的组织。这应该适用于每个控制器Asp.net core 如何将租户/组织id添加到每个URL并在控制器中读取,asp.net-core,asp.net-core-mvc,multi-tenant,Asp.net Core,Asp.net Core Mvc,Multi Tenant,我正在编写一个ASP.NET核心web应用程序。在我的应用程序中,用户可以是一个或多个组织的成员(此信息存储在数据库中)。我想让用户可以选择整个应用程序应该运行的组织上下文。这个上下文应该传递给每个控制器,这样我就可以进行适当的检查并只返回所选组织的数据 换句话说,我希望达到用户可以通过以下方式访问应用程序的状态: app.mydomain.com/org1/controller/action/id并使用下拉菜单,他们应该能够切换到org2并访问app.mydomain/org2/control
如何做到这一点?是否有可能构建一个路由来处理它,并只向每个控制器添加新参数,例如orgId?或者应该有一个从URL读取这些信息并可以注入控制器的服务?那么路线会是什么样子呢?我已经阅读了一些关于以类似方式处理多种语言(URL中包含文化)的教程,但我无法将其转换为我的案例。有关如何将选择的组织id传递给控制器的信息:
public class OrgnizationController : Controller
{
public IActionResult Test(string select)
{
//the select is the value you choose
//do your stuff....
return View();
}
}
public class OrgnizationController : Controller
{
public IActionResult Test(string select)
{
var org = "";
if (select==null)
{
var path = Request.Path.ToString();
org = path.Split('/')[1];
}
//do your stuff....
return View();
}
}
视图:
如果要向路由添加前缀并在控制器中获取前缀:
public class OrgnizationController : Controller
{
public IActionResult Test(string select)
{
//the select is the value you choose
//do your stuff....
return View();
}
}
public class OrgnizationController : Controller
{
public IActionResult Test(string select)
{
var org = "";
if (select==null)
{
var path = Request.Path.ToString();
org = path.Split('/')[1];
}
//do your stuff....
return View();
}
}
Startup.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{orgid?}/{controller=Home}/{action=Privacy}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Privacy}/{id?}");
});
控制器:
public class OrgnizationController : Controller
{
public IActionResult Test(string select)
{
//the select is the value you choose
//do your stuff....
return View();
}
}
public class OrgnizationController : Controller
{
public IActionResult Test(string select)
{
var org = "";
if (select==null)
{
var path = Request.Path.ToString();
org = path.Split('/')[1];
}
//do your stuff....
return View();
}
}
结果:
您的控制器怎么样?org1和org2是否可以访问同一个控制器,但在该控制器中,可以读取自身的组织?org1和org2以及以后可以添加到DB的任何其他组织的整个应用程序逻辑都是相同的。唯一的区别是背后的数据。因此,是的,任何组织都应该能够访问相同的控制器,我唯一需要的是读取控制器中的组织,以便返回正确的数据。非常感谢您的帮助。我不得不在路由方面多做一些尝试,但这个概念起了作用。