c# using custom attributes to validate prerequisites for methods, controller APIs

If you have bunch of prerequisites to be validated for more than one method, we could make code more cute by using an attribute.

For normal methods, this new custom attribute’s constructor could throw exception in case of failure.

But throwing exception in Controller API is bad idea. We want to return more gracefully.

Instead of extending Attribute, extend AuthorizeAttribute and override IsAuthorized() [ or AuthorizeCore() ] method to return true or false. This is more graceful way of doing prerequisite check.

I know this AuthroizeAttribute is to check authorization, but we could mis-use it to validate any prerequisites until a better way is available.

/*****************************************************************************************/

using System;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
internal class MustBeAuthorizedAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{

if (preRequsitesFail)

{
return false;

}

return true;
}
}
}

/*****************************************************************************************/

[MustBeAuthorized]
public ActionResult Index()
{
return View();
}

/*****************************************************************************************/

Thanks to @philip instead of AuthroizeAttribute  ActionFilterAttribute is better. We could return any return value (e.g.. MethodNotAllowed, InternalServerError); see https://stackoverflow.com/questions/16822365/web-api-how-to-stop-the-web-pipeline-directly-from-an-onactionexecuting-filter 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.