c# - asp.net MVC自定义Authorize属性,传递参数和方法细节

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

我正在尝试创建 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);
}

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

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(Entity = "Invoice", Key = "InvoiceNumber", Value = invoiceNumber)]
public ActionResult InvoiceModal(string invoiceNumber)

关于c# - asp.net MVC自定义Authorize属性,传递参数和方法细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52152841/

相关文章:

c# - 使用正则表达式将长度在 2 到 8 之间的数字替换为特定字符

asp.net-mvc - ASP.NET MVC 子域授权

Python调用类函数作为其他类属性

ruby-on-rails - 在模型的属性名称中包含 "ID"

c# - ASP.NET Core 类型化客户端中的 IHttpClientFactory

c# - 对于我按下的每个按钮,打开相同的表单。(C#)

javascript - AJAX Post to Controller 未正确设置 VIewModel 参数

class - yii2详细 View 条件行类

c# - 如何使 TextBox 使用密码字符而不是在 wpf 中使用密码框?

c# - 获取第一个表插入的值到第二个表