c# - ASP.NET MVC, 'Ticket Required' 属性

标签 c# asp.net-mvc castle-windsor

我正在尝试构建一个允许用户执行某些操作的系统,但他们的帐户每次执行此操作时都必须有一个特定的“票证”。例如,假设他们希望创建一个 Product,他们将需要一个 CreateProductTicket

当然,我可以简单地使用一些“if”语句来做到这一点,但我想尝试更多的稳健解决方案。我的结构看起来像这样......

interface ITicket<T> where T : ITicketable
{
}

我的基本目标是构建一个属性,可能如下所示......

public class TicketRequiredAttribute : Attribute
{
 public TicketRequiredAttribute(ITicket<T> ticket)
 {
  if(ticket == null) 
    return;
  }
}

并且能够用它装饰 Controller Repository Actions。好喜欢……

产品 Controller

[TicketRequired(CreateProductTicket)]
public ActionResult CreateProduct(Product product)
{
 // ... **I am unsure how to tell if TicketRequired was true or not**
}

问题1

我对属性不够熟悉,不知道如何判断 TicketRequired 是否被“满足”。任何人都可以启发我吗?

问题2

我遇到的问题是数据库查询。我希望能够检查用户(IMembershipRepository 有一个 GetUser 方法),但我不完全确定如何通过属性来做到这一点。

使用 CaSTLe.Windsor,我将依赖注入(inject)设置为将存储库注入(inject) Controller 。我想我可以通过 TicketRequired 构造函数传递 IMembershipRepository,但我有一种感觉,它会变得非常困惑 - 并且极其不稳定。有没有更合乎逻辑的方法来解决这个问题?

最佳答案

你快到了。您可以在 http://www.asp.net/mvc/tutorials/understanding-action-filters-cs 找到更多详细信息。

我只会在操作中使用该属性,因为该网站是我进行所有授权的地方。

这是一个可能的解决方案。我没有测试过这个,但它应该可以工作。您需要验证我重定向的方式,不确定这是否是正确的方式。

 public class TicketRequiredActionFilter : ActionFilterAttribute
 {
        private Type _ticketType;

  public TicketRequiredAttribute(Type ticketType)
  {
        _ticketRequired = ticketType;     
  }

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     UserServices userServices = GetUserServicesViaDIContainer(); // you'll need to figure out how to implement this 
     string userId = filterContext.HttpContext.User.Identity.Name
     bool hasTicket = userServices.HasTicket(_ticketType, (int)userId); // again, you'll need to figure out the exact implementation
     if(!hasTicket)
     {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, {"action", "NoPermission" } })
     }
     else
     { 
        base.OnActionExecuting(filterContext);
     }     
  }
}

在你的 Controller 中:

[TicketRequiredActionFilter(typeof(CreateProductTicket))]
public ActionResult MyMethod()
{
    // do stuff as if the person is authorized and has the ticket
}

如果用户没有票,则重定向有问题;否则,照常继续。

关于c# - ASP.NET MVC, 'Ticket Required' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4511496/

相关文章:

c# - 将 ASP.NET MVC View 返回为 HTML 文件,以便在电子邮件模板中使用

asp.net-mvc - Azure Active Directory、OWIN 和 ASP .NET MVC

c# - 使用 CaSTLe Windsor 单例是在 ASP.NET 中缓存只读数据的有效方法

wcf - 为什么使用 CaSTLe Windsor 实现的 IIS 托管 WCF 服务需要基地址?

c# - 如何将字符串从编码代码转换为字符?

c# - 具有引用成员的结构 : heap or stack?

c# - 如何从下拉列表中获取选定的值

nhibernate - 如何使用 LifestyleScoped 实现 CaSTLe Windsor IScopeAccessor 以提供每个 ViewModel 的 NHibernate session

c# - 为什么我得到这个 NullReferenceException C#

c# - 如何为 .NET 应用程序域重新加载程序集?