Reputation: 399
I am trying to create a MVC Custom Authentication Attribute.
I have this method as follows:
[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);
}
Below is the attribute I have created so far, I am struggling to pass the values form the controller attribute to the attribute, please see the attribute class below:
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..
}
}
This will be required on multiple actions so how do I get the required data / fields on the custom attribute?
Upvotes: 4
Views: 4383
Reputation: 728
This looks like it should work. Passing the values to the constructor like this is acceptable.
You could try removing them from the constructor and doing the following:
[CustomerContextRequiredAttribute(Entity = "Invoice", Key = "InvoiceNumber", Value = invoiceNumber)]
public ActionResult InvoiceModal(string invoiceNumber)
Upvotes: 1