Archive

Archive for August, 2015

ASP.NET MVC: Disable Controller

August 3rd, 2015 Admin No comments

    If you want to disable a MVC Controller, not deleting it, a good way to do that is apply a custom ActionFilter-derived attribute to it. Don’t confuse the ActionFilterAttribute defined in the System.Web.Mvc (the one we’re going to use) with the attribute of the same name residing within the Web API infrastructure, namely in the System.Web.Http.Filters namespace.

So, the custom attribute could be defined like

public class DisableControllerAttribute : ActionFilterAttribute
{
	public override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		//filterContext.Result = new HttpNotFoundResult();
		throw new HttpException((int)HttpStatusCode.NotFound, null);
	}
}

Applying it to the target MVC Controller is as simple as follows

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

[DisableController]
public class SomeLegacyController : Controller
{
}

Calling any action of such MVC contoller, user gets the 404 Http Status Code page. The page could look differently depending on which way you use to return the Status Code. Using the first line of code in the DisableControllerAttribute.OnActionExecuting (currently commented), the IIS “native” 404 page will be returned.

IIS Native 404 page not found

Throwing the HttpException like shown in the second line of the DisableControllerAttribute.OnActionExecuting (uncommented), you’ll get the ASP.NET handled page.

ASP.Net 404 page not found