gpt4 book ai didi

asp.net-mvc - 我如何使用HttpResponseMessage HttpStatusCode分隔web.config httpErrors

转载 作者:行者123 更新时间:2023-12-03 08:50:26 26 4
gpt4 key购买 nike

我正在使用asp.net mvc开发应用程序

我正在发送ajax发布请求。

操作过程中发生错误时,我得到500个状态代码。

这种情况是正确的,但是web.config文件中的代码重定向到错误页面。

这是我的代码

    public class ErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;

filterContext.ExceptionHandled = true;

response.StatusCode = (int)HttpStatusCode.InternalServerError;

filterContext.Result = new JsonResult
{
Data = new {

success = false
},

JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}

Web配置
<httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" errorMode="Custom">
<remove statusCode="500"/>
<error statusCode="500" path="/common/error" responseMode="Redirect"/>
</httpErrors>

最佳答案

一点建议

发生异常时,不要一直将response.StatusCode设置为HttpStatusCode.InternalServerError。请尝试并更具体一些,这样您就不会总是返回500。如果您返回另一个更具体的错误代码,则根据web.config不会发送重定向。例如,如果错误是由于ajax请求了具有特定ID的用户而该用户不存在,则返回错误代码404。

现在要解决您的问题,您可以执行以下操作:

if (filterContext.HttpContext.Request.IsAjaxRequest())
{
CallbackException error = new CallbackException();
error.message = errorMessage;
error.isCallbackError = true;
error.stackTrace = stackTrace;

JSONSerializer Serializer = new JSONSerializer();
string result = Serializer.Serialize(error);

var response = filterContext.RequestContext.HttpContext.Response;
response.ContentType = ControlResources.STR_JsonContentType;

response.TrySkipIisCustomErrors = true;
response.StatusCode = 500;
response.Write(Result);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
// The code in your answer goes here
}

如果有兴趣,请参阅 this文章以获取更多详细信息。

关于asp.net-mvc - 我如何使用HttpResponseMessage HttpStatusCode分隔web.config httpErrors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42472886/

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