【问题标题】:asp.net MVC custom Authorize attribute, passing parameters and method detailsasp.net MVC 自定义 Authorize 属性,传递参数和方法细节
【发布时间】:2023-03-04 04:31:01
【问题描述】:

我正在尝试创建 MVC 自定义身份验证属性。

我有这个方法如下:

[DealerContextRequired]
[CustomerContextRequiredAttribute("Invoice", "InvoiceNumber", invoiceNumber)]
public ActionResult InvoiceModal(string invoiceNumber)
{
    if (!Request.IsAjaxRequest())
       return RedirectToAction("InvoiceModal", "Orders", new { area = "my_account", headerNumber = invoiceNumber });

    InvoiceHeader invoice = _invoiceReader.Get(invoiceNumber, false);

    if (_dealerContext.CurrentFranchisee != null)
    {
       var order = _orderReader.GetByInvoiceNumber(invoice.InvoiceNumber).FirstOrDefault();
       if (order == null)
             return HttpNotFound();

       if (order.Franchisee == null || _dealerContext.CurrentFranchisee.Key != order.Franchisee.Key)
            return new HttpUnauthorizedResult();
    }

    return PartialView("InvoiceModal", invoice);
}

下面是我到目前为止创建的属性,我正在努力将值从控制器属性传递给属性,请参阅下面的属性类:

public class CustomerContextRequiredAttribute : System.Web.Mvc.AuthorizeAttribute
{
    public object Entity { get; set; }

    public string Key { get; set; }

    public int Value { get; set; }
    public CustomerContextRequiredAttribute(object entity, string key, int value)
    {
        this.Entity = entity;
        this.Key = key;
        this.Value = value;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var customerContext = DependencyResolver.Current.GetService<CustomerContext>();
        var _customerReader = DependencyResolver.Current.GetService<ICustomerReader>();

        var entity = this.Entity;
        var key = this.Key;
        var value = this.Value;

        // some logic required for the attribute I am creating based on the above three values..

    }
}

这将是多项操作所必需的,那么如何在自定义属性上获取所需的数据/字段?

【问题讨论】:

  • 控制器中的属性参数值在CustomerContextRequiredAttribute类的OnAuthorization方法中不可用?
  • 恕我直言,我不确定这应该作为“授权过滤器”实现。 似乎您只想确保Invoice 存在,而不是检查请求是否被授权(谁不是什么)?

标签: c# asp.net-mvc attributes custom-attributes


【解决方案1】:

这看起来应该可以工作。像这样将值传递给构造函数是可以接受的。

您可以尝试从构造函数中删除它们并执行以下操作:

[CustomerContextRequiredAttribute(Entity = "Invoice", Key = "InvoiceNumber", Value = invoiceNumber)]
public ActionResult InvoiceModal(string invoiceNumber)

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多