从控制器构造函数中的URL获取参数 [英] get parameters from URL in controller constructor

查看:124
本文介绍了从控制器构造函数中的URL获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一些代码来在我的项目数据库中找到一个ID. 用户耦合到一个项目,并且所有项目都与其他对象(例如会话)建立了很多连接.

I need to write some code to find an ID in my database of a Project. Users are coupled to a project and all the projects have a lot of connections to other objects, such as Sessions.

现在我需要在运行任何操作之前进行检查,如果试图访问会话的用户是否连接到与会话连接相同的项目.

Now I need to check before running any Actions, if the user trying to access the Session, is connected to the same project as the session is connected to.

为此,我想在Actions上使用[Attribute]. MVC:创建带有参数的自定义[AuthorizeAttribute]吗?

For this i want to use an [Attribute] on the Actions. MVC: creating a custom [AuthorizeAttribute] which takes parameters?

这个问题和答案让我开始,但是我在使用控制器的构造函数来获取我的Project ID

This question and answer got me started, but i'm having trouble using the constructor of the controller to get my Project ID

目标是我可以根据项目在我的所有对象控制器的每个构造函数中编写一些代码,找到项目ID,并使其可访问(公共),因此我的[customauthorize]将可以访问此代码项目ID,以检查用户是否具有访问权限.

the goal is that i can write some code in each constructor, of all my controllers of objects depending on the Projects, find the project ID, and make it accessible (public), so my [customauthorize] will have access to this project ID to check whether the user has access or not.

我的问题:

public class SessionController : Controller {

    NASDataContext _db = new NASDataContext();


    public SessionController() {
        var test = RouteData;
        var ses = _db.Sessies.First(q=>q.Ses_ID==1);
    }

如何访问我的路线数据? RouteData为空,HttpContext为空,Request为空.

How do I access my routedata? RouteData is null, HttpContext is null and Request is null.

我需要URL中的ID,该ID在routedata中...

I need the ID in the url, which is in the routedata...

推荐答案

我建议将此检查放在模型而不是控制器中.在Controller中,您需要装饰需要此检查的每个动作,请记住,这是在您对其应用的每个动作上执行代码,因此您可能不希望一开始就在Controller级别上应用它.比较简单的方法是在模型中实施一次检查,然后您的控制器中就没有访问权限的顾虑".这样一来,就可以对该访问权限检查进行测试,因为您只能将测试放在一个地方.

I would suggest placing this check in the Model rather than the Controller. In the Controller you'll need to decorate each action that requires this check, remember this is going execute code on every action you apply it to so you probably don't want to apply it at Controller level to start with. The simpler approach is to implement the check once in the Model then you have no 'concern' in your Controller for access rights. This will make the testing of this access right check possible as you'll only have the test in one place.

这篇关于从控制器构造函数中的URL获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆