I am working on a new business object class, wherein I have used several authorization rules to control whether certain methods and properties can be used. eg:
BusinessRules.AddRule(new CanWritePropertyRule<Task>(TimeProperty,x => !x.IsCancelled && !x.IsCompleted));
I would like meaningful error/reason messages to appear when I call CanWriteProperty. If IsCompeted == true, it should say "Cannot set time on Completed Task", and when IsCancelled == true, it should say "Cannot set time on Cancelled Task".
This is a specific example, but I need to do this for many properties and methods.
However, I can't see how I can use AuthorizationRules for this, since they give no message.
Here is my action:
public ActionResult TaskTime(int id)
if (!ValidateViewModel(id, this.InitializeViewModel))
return JsonHtmlContentError("Error", null);
ModelState.AddModelError("JsonError", "Cannot edit Time");
So rather than just "Cannot edit Time", I need to explain why this is the case. My initial thought is that I need to write a custom rule and somehow call that rule directly. something like PropertyRule's broken rules collection would be nice to have.
Authorization rules by nature only return true or false (has acess or not).
But - if you look at the overload
public bool CanWriteProperty(Csla.Core.IPropertyInfo property, bool throwOnFalse)
You can also throw an Exception, f.ex Csla.Security.SecurityException and you may also throw an exception with a contextual message from within the AuthorizationRules Execute method.
It is the only way that I know of to get a contextual message back to the UI / Client from an authorization rule.
Also remember to set CacheResult = false on your AuthorizationRule.
The problem is, I need a different message for each and every fail reason. The reasons are not always mutually exclusive, so I will possibly need multiple reasons to be displayed.
I don't know if this solution will work, as it only allows me to set one string - the exception's Message property. I suppose I could override SecurityException to allow multiple messages. Or even create a custom authorization rule and custom authorization context to store my messages?
Copyright (c) Marimer LLC