gpt4 book ai didi

c# - 你能用参数做一些像 RoutePrefix 这样的事情吗?

转载 作者:太空狗 更新时间:2023-10-29 17:39:08 26 4
gpt4 key购买 nike

我想知道我是否可以做类似 RoutePrefix("{projectName}/usergroups") 的事情,因为我有很多项目,每个项目都包含用户组。现在,在每个 Usergroup Controller 中,我首先需要获取它所绑定(bind)的 Project。这可能吗?

我尝试了什么

我尝试简单地执行 RoutePrefix("projects/{projectName}") 然后将其传递给 Controller ​​构造函数,但它不是那样工作的。我还尝试在 Controller 级别使用 Route 而不是 RoutePrefix 但我的内部路由不起作用。

代码

[RoutePrefix("projects"), Authorization]
public class UsergroupController : Controller
{
private readonly Project _project; // i would like to inject it here on constructor
private readonly Account _account;
private readonly IProjectRepository _projectRepository;

public UsergroupController(IAuthorizationService auth, IProjectRepository projectRepository)
{
_projectRepository = projectRepository;
_account = auth.GetCurrentAccount();
}

[Route("{projectName}/usergroups"), HttpGet]
public ActionResult Index(string projectName)
{
// the problem that i will need to pass projectName
// to every action and do this check in every action as well
//
// looks like totally ugly code-duplication
var project = _projectRepository
.GetByAccountId(_account.Id.ToString())
.SingleOrDefault(x => x.Name == projectName);

if (project == null)
{
return HttpNotFound();
}

// now get all usergroups in this project e.g. project.Usergroups

return null;
}
}

最佳答案

你可以有一个带参数的路由前缀,但你的操作方法仍然必须接受参数,就好像它是它们路由的一部分一样。您无法满足 Controller 构造函数的依赖:

[RoutePrefix("{projectName}/usergroups")]
public class UsergroupController : Controller
{
[Route("")]
public ActionResult Index(string projectName)
{
...
}
}

关于c# - 你能用参数做一些像 RoutePrefix 这样的事情吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24249347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com