gpt4 book ai didi

json - 如何从 global.asax 中的 App_Error 以 json 格式返回异常数据?

转载 作者:行者123 更新时间:2023-12-04 05:26:47 26 4
gpt4 key购买 nike

我正在将 Asp.net MVC 项目作为用于错误处理的单页应用程序。我想从 Application_Error 返回 json 数据global.asax 中的方法到 UI 并通过 jQuery 显示它或调用 Controller 并返回 partialView。
我不想刷新页面或将其重定向到错误页面。

最佳答案

这是要走的路

protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();

// if the error is NOT http error, then stop handling it.
if (!(exception is HttpException httpException))
return;

if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
Response.Clear();
Response.TrySkipIisCustomErrors = true;
Server.ClearError();

Response.ContentType = "application/json";
Response.StatusCode = 400;
JsonResult json = new JsonResult
{
Data = exception.Message
};

json.ExecuteResult(new ControllerContext(Request.RequestContext, new BaseController()));
}
}

关于json - 如何从 global.asax 中的 App_Error 以 json 格式返回异常数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13121149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com