Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
FailRequestAttribute
using System;
using System.Net;
using System.Threading;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute;
namespace MyProject
{
/// <summary>
/// Always fails the current HttpRequestMessage. Used for error handling development in front-end UIs.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class FailRequestAttribute : ActionFilterAttribute
{
/// <summary>
/// The HttpStatusCode to include in the error response.
/// </summary>
public HttpStatusCode StatusCode = HttpStatusCode.InternalServerError;
/// <summary>
/// An error message to be sent in the description of the error.
/// </summary>
public string ErrorMessage;
/// <summary>
/// How long of a delay to introduce before the error occurs. Use to simulate timeouts.
/// </summary>
public int Delay = 0;
private const string DefaultErrorMessage = "Automatic error generated. This is caused by the FailRequest ActionFilter. To stop this error, remove the attribute from the class or method.";
public override void OnActionExecuting(HttpActionContext filterContext)
{
if (ErrorMessage == null)
{
ErrorMessage = string.Format("{0}. This error was fired on the {1} Action of the {2} Controller.",
DefaultErrorMessage, filterContext.ActionDescriptor.ActionName,
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName);
}
Thread.Sleep(Delay);
throw new HttpResponseException(filterContext.Request.CreateErrorResponse(StatusCode, ErrorMessage));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.