Created
September 19, 2012 16:46
-
-
Save kenstone/3750711 to your computer and use it in GitHub Desktop.
FailRequestAttribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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