gpt4 book ai didi

jquery - OnActionExecuting 事件未返回 jsonResult

转载 作者:行者123 更新时间:2023-12-01 07:52:15 30 4
gpt4 key购买 nike

我创建了一个 ActionFilterAttribute,用于在允许处理 MVC Controller get/post 请求之前验证帐户是否可用于处理。如果该帐户不可用,我想向客户返回错误。如果请求是 ajax post,我想在响应中包含 json 数据。由于某种原因,只有当浏览器和网站在同一台机器上运行时,json 数据才会返回到浏览器。如果我在另一台计算机上浏览该网站并执行 ajax post,则响应内容类型将返回为“text/html”。但是,如果浏览器与网站在同一台计算机上运行,​​则响应内容类型将正确返回为“application/json”。

我做错了什么?

ActionFilter属性

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);

if (filterContext.Result == null)
{
if (IsAccountUnavailable(Key))
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
filterContext.HttpContext.Response.ContentType = "application/json";
filterContext.Result = new JsonResult
{
Data = new {Error = "Unavailable", Url = GetLogOffUrl()},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
filterContext.Result = new RedirectResult(GetLogOffUrl());
}
}
}

jQuery ajax 帖子

$.ajax({
url: window.location.href,
type: 'POST',
data: JSON.stringify(ko.mapping.toJS(serverModel.SelectionsViewModel)),
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function (data) {
if (data.isValid)
window.location.href = serverModel.NextView();
else
showGenericSaveError();
})
.fail(function (jqXhr) {
handleAjaxError(jqXhr);
});
};

最佳答案

感谢一位同事发现了以下帖子,我的问题已得到解决。我需要设置 Response.TrySkipIisCustomErrors = true

Returning http status code 409 Conflict (without ASP.NET MVC alterations)

工作代码...

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);

if (filterContext.Result == null)
{
if (QuoteServiceLayer.IsAccountUnavailable(AccountKey, EnrollmentPeriodType, EmployeeKey))
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.Result = new JsonResult
{
Data = new {Error = "Unavailable", Url = GetLogOffUrl()},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
filterContext.Result = new RedirectResult(GetLogOffUrl());
}
}
}

关于jquery - OnActionExecuting 事件未返回 jsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28489275/

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