ASP.NET MVC 2.0 - 禁用控制器/操作的自定义错误重定向

发布于 2024-10-13 16:27:27 字数 1576 浏览 5 评论 0原文

我有一个控制器,其中包含一系列返回 jsonp 的操作。我的问题是,启用自定义错误后,当出现硬服务器错误时,我的 jquery ajax 调用不会“错误”。因此,我需要仅针对控制器禁用自定义错误重定向,或者如果必须的话,针对该控制器中的每个操作禁用自定义错误重定向。

当仅在这些操作上发生错误时,有什么方法可以禁用重定向,但仍然向客户端返回错误代码,以便 ajax 可以处理错误?

编辑:

我将用一些代码进行扩展。首先,我使用自定义错误配置。

<customErrors mode="RemoteOnly" defaultRedirect="~/Error/ServerError">
  <error statusCode="403" redirect="~/Error/AccessDenied" />
  <error statusCode="404" redirect="~/Error/NotFound" />
  <error statusCode="500" redirect="~/Error/ServerError" />
  <error statusCode="999" redirect="~/Error/ServerError" />
</customErrors>

然后,我有自己的异常报告属性。此属性应用于实现 IController 的基本控制器类。我的所有控制器都继承自此基本控制器,因此只要出现服务器错误,它们都会内置错误报告。

public sealed class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        RaiseErrorSignal(context.Exception);
    }

    private static void RaiseErrorSignal(Exception ex)
    {
        IExceptionHandler handler = Resolve();

        handler.HandleError(ex.GetBaseException());
    }

    private static IExceptionHandler Resolve()
    {
        return ServiceLocator.Locate<IExceptionHandler>();

    }
}

我有一个带有这样的方法的控制器

public JsonpResult DoSomething(string sessionId /*...more params...*/)
{
    //Do work

    return new JsonpResult() { Data = new { } };
}

仅在这个控制器/这些操作上,我想禁用重定向,以便将错误代码返回给客户端。仍然需要抛出错误,但不知何故需要将自定义错误模式更改为“关闭”,仅针对此请求以及仅在请求的持续时间内。

I have a controller with a series of actions that return jsonp. My problem is that with custom errors enabled, my jquery ajax calls do not "error" when there is a hard server error. So, I need to disable custom error redirection just for the controller, or if I have to, for each action in that controller.

Is there any way that I can disable the redirection when an error happens only on those actions, but still return an error code to the client so that ajax can handle the error?

EDIT:

I'll expand with some code. Firstly, I am using the configuration for custom errors.

<customErrors mode="RemoteOnly" defaultRedirect="~/Error/ServerError">
  <error statusCode="403" redirect="~/Error/AccessDenied" />
  <error statusCode="404" redirect="~/Error/NotFound" />
  <error statusCode="500" redirect="~/Error/ServerError" />
  <error statusCode="999" redirect="~/Error/ServerError" />
</customErrors>

Then, I have my own exception reporting attribute. This attribute is applied to a base controller class that implements IController. All of my controllers inherit from this base controller, so that they all have error reporting built in any time there is a server error.

public sealed class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        RaiseErrorSignal(context.Exception);
    }

    private static void RaiseErrorSignal(Exception ex)
    {
        IExceptionHandler handler = Resolve();

        handler.HandleError(ex.GetBaseException());
    }

    private static IExceptionHandler Resolve()
    {
        return ServiceLocator.Locate<IExceptionHandler>();

    }
}

And I have a controller with methods like this

public JsonpResult DoSomething(string sessionId /*...more params...*/)
{
    //Do work

    return new JsonpResult() { Data = new { } };
}

On only this controller/these actions, I want to disable the redirection so that the error code is returned to the client. The error still needs to be thrown, but somehow the custom error mode needs to be changed to Off for only this request and only the duration of the request.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

策马西风 2024-10-20 16:27:27

我接受了@frennky 提供的答案并对其进行了一些扩展。我正在设置 HTTP 响应代码并让 jQuery 端的错误处理程序处理它。

就我而言,我正在与旧版 Web 表单应用程序集成,该应用程序使用 ASP.NET 自定义错误页面来捕获我的所有错误。所有异常都被吞掉,jQuery AJAX 调用似乎正常完成。自定义错误页面的 HTML 返回到我的 jQuery AJAX 成功函数。我想要一种利用 jQuery 提供的错误处理的方法。这种方法实现了这一目标。

这是我的自定义 HandleErrorAttribute:

public class HandleAjaxErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            base.OnException(filterContext);
            return;
        }
        else
        {
            //Log the error here.
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
        }
    }
}

这是我的 Javascript 函数,当 jQuery AJAX 请求失败时会调用该函数(对于本示例进行了简化):

function HandleAjaxError(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.statusText);
}

I took the answer provided by @frennky and expanded on it a little bit. I am setting the HTTP response code and letting the error handler on the jQuery side handle it.

In my case I am integrating with a legacy webforms app that uses an ASP.NET custom error page that trapped all of my errors. All execeptions were being swallowed and the jQuery AJAX call appeared to complete normally. The HTML of the custom error page was being returned to my jQuery AJAX success function. I wanted a way to utilize the error handling provided by jQuery. This approach accomplishes that goal.

Here is my custom HandleErrorAttribute:

public class HandleAjaxErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            base.OnException(filterContext);
            return;
        }
        else
        {
            //Log the error here.
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
        }
    }
}

Here is my Javascript function that gets called when the jQuery AJAX request fails (simplified for this example):

function HandleAjaxError(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.statusText);
}
不再见 2024-10-20 16:27:27

如果这些是 ajax 调用,您可以尝试这样的操作:

public sealed class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            base.OnException(context);
            RaiseErrorSignal(context.Exception);
        }
        else
        {
            //Respond to ajax call with error message
        }
    }
    //...
}

If these are ajax calls, you could try something like this:

public sealed class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            base.OnException(context);
            RaiseErrorSignal(context.Exception);
        }
        else
        {
            //Respond to ajax call with error message
        }
    }
    //...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文