我正在尝试构建一个允许用户执行某些操作的系统,但他们的帐户每次执行此操作时都必须有一个特定的“票证”。例如,假设他们希望创建一个 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/