c# - 对 302 状态代码使用 handleexeption 注释时如何指定位置

标签 c# asp.net-mvc visual-studio asp.net-web-api2 webapi2

使用 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# - 对 302 状态代码使用 handleexeption 注释时如何指定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35586593/

相关文章:

c# - Windows 应用商店应用程序的 Socket.ConnectAsync 不喜欢 Async

c# - Foreach 循环 - 长字符串的性能

asp.net-mvc - Telerik mvc 网格 ForeignKey 列

jquery - Bootstrap datetimepicker 出现在窗口的左上角

c# - 开始为 PowerPoint 开发插件

visual-studio - Windows Phone 8.1 模拟器卡在启动操作系统

c# - 如何将我的应用程序与 Windows 7 任务栏上的固定程序相关联?

c# - C#中的另一个项目引用时如何使用已编译项目复制非代码文件

javascript - 为什么这个 JQuery 函数只能与 post 一起使用?

c# - DurandalAuth 2.0.1 的 Weyland 构建失败