你能用参数做一些类似RoutePrefix的东西吗?

时间:2014-06-16 17:47:30

标签: c# asp.net-mvc routes asp.net-mvc-5

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

我尝试了什么

我只是尝试RoutePrefix("projects/{projectName}")然后在控制器构造函数中传递它,但它不能像那样工作。我还尝试在控制器级别上使用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;
    }
}

1 个答案:

答案 0 :(得分:15)

您可以拥有一个带参数的路由前缀,但您的操作方法仍然必须接受该参数,就像它是路径的一部分一样。您无法满足控制器构造函数的依赖性:

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