HandleExceptionAttribute

HandleExceptionAttribute

使用C#Web Api 2,我有抛出InvalidOperationException的代码。当返回状态码302时,如何使用HandleException批注提供重定向的位置?

[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");
     }
}

编辑:
抱歉,我急忙问了这个问题。上面的类使用从ExceptionFilterAttribute继承的HandleExceptionAttribute类。在尝试调试他们的单元测试时,我没有意识到这一点。该问题不会在单元测试中出现,但会使用需要重定向URL的Visual Studio .webtest出现。从ExceptionFilterAttribute继承的类未提供允许提供重定向URL的参数。抱歉,问题不完整,感谢您抽出宝贵的时间回答。
/// <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
   {

最佳答案

编辑:感谢您更新问题。尽管我仍然不确定,为什么要在此WebApi方法中进行重定向。希望这个答案可以有所帮助。

我将处理HandleExceptionAttribute中的所有异常逻辑。您甚至可以使用您要查找的302代码从那里重定向。您的HandleExceptionAttribute看起来像这样(我包括3种不同的基于异常返回结果的方式):

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.");
    }
}

但是,如果您确实希望按照您的要求完成操作,则可以在GetHandleException方法中添加第二个参数。这将接收一个消息字符串(或URL),然后在HandleExceptionAttribute中将重定向URL添加到参数(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");
    }
}

然后,您的HandleExceptionAttribute如下所示:
public sealed class HandleExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        context.ActionContext.ActionArguments["message"] = "your redirect URL";

    }
}

关于c# - 将handleexeption批注用于302状态代码时,如何指定位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35586593/

10-12 00:25