Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you specify the location when using handleexeption annotation for a 302 status code

Using c# Web Api 2, I have code that throws an InvalidOperationException. When returning a status code of 302, how do provide a location for the redirect using the HandleException annotation?

[HandleException(typeof(InvalidOperationException), HttpStatusCode.Found, ResponseContent = "Custom message 12")]
public IHttpActionResult GetHandleException(int num)
{
     switch (num)
     {
          case 12: throw new InvalidOperationException("DONT SHOW invalid operation exception");

          default: throw new Exception("base exception");
     }
}

Edit: Sorry, I asked this question in a bit of haste. The above class uses a HandleExceptionAttribute class which inherits from ExceptionFilterAttribute. I didn't realize this at the time I was trying to debug their unit test. The problem doesn't arise in a unit test, but does show up using a Visual Studio .webtest that requires the redirect url. The class that inherits from ExceptionFilterAttribute did not provide a parameter that allows for the redirected URL to be supplied. Sorry for an incomplete question and thanks for taking time to answer.

/// <summary>
   /// This attribute will handle exceptions thrown by an action method in a consistent way
   /// by mapping an exception type to the desired HTTP status code in the response.
   /// It may be applied multiple times to the same method.
   /// </summary>
   [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
   public sealed class HandleExceptionAttribute : ExceptionFilterAttribute
   {
like image 625
TheEmirOfGroofunkistan Avatar asked Feb 23 '16 19:02

TheEmirOfGroofunkistan


1 Answers

Edited: Thanks for updated the question. Although I'm still not exactly sure why you would want to redirect in this WebApi method. Hopefully this answer can help though.

I would handle all the exception logic in the HandleExceptionAttribute. You could even redirect from there with the 302 code you are seeking. Your HandleExceptionAttribute would look like this(I've included 3 different ways of returning a result based on an exception):

public sealed class HandleExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        //TODO: we can handle all types of exceptions here. Out of memory, divide by zero, etc etc.
        if (context.Exception is InvalidOperationException)
        {
            var httpResponseMessage = context.Request.CreateResponse(HttpStatusCode.Redirect);
            httpResponseMessage.Headers.Location = new Uri("http://www.YourRedirectUrl");
            throw new HttpResponseException(httpResponseMessage);
        }
        if (context.Exception is UnauthorizedAccessException)
        {
            context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, context.Exception.Message);
            return;
        }
        if (context.Exception is TimeoutException)
        {
            throw new HttpResponseException(context.Request.CreateResponse(HttpStatusCode.RequestTimeout, context.Exception.Message));
        }

        context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to process your request.");
    }
}

However if you really want it done the way you ask, you could add a second parameter to your GetHandleException method. This would take in a message string(or URL) then in your HandleExceptionAttribute you would add the redirect url to the parameter(ActionArguements) :

public IHttpActionResult GetHandleException(int num, string message = "")
{
    switch (num)
    {
        case 12: return Redirect(message); //message string would be your url

        default: throw new Exception("base exception");
    }
}

Then your HandleExceptionAttribute looks like this:

public sealed class HandleExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        context.ActionContext.ActionArguments["message"] = "your redirect URL";

    }
}
like image 171
Andrew M. Avatar answered Sep 26 '22 16:09

Andrew M.