我正在使用knockout并使用下面给出的自定义函数对控制器进行ajax调用。如果发生任何未处理的异常,它会返回整个页面作为响应,这会导致响应显示整个页面的html,请建议正确的处理方式
function asyncComputed(evaluator, owner) {
var result = ko.observable(), currentDeferred;
result.inProgress = ko.observable(false); // Track whether we're waiting for a result
ko.computed(function () {
// Abort any in-flight evaluation to ensure we only notify with the latest value
if (currentDeferred) { currentDeferred.reject(); }
var evaluatorResult = evaluator.call(owner);
// Cope with both asynchronous and synchronous values
if (evaluatorResult && (typeof evaluatorResult.done == "function")) { // Async
result.inProgress(true);
currentDeferred = $.Deferred().done(function (data) {
result.inProgress(false);
if (data.hasOwnProperty("HasFailed") == true && data.ErrorCode == 1)//For Session Time Out
{
$("#timeoutmessage")
.html('<div class="modal-backdrop">' +
'<div style="color:white;" class="middle">' +
'<div class="row-fluid"><div>Your session has timed out, please <a href="/">Login here </a>again.</div></div>' +
'</div>')
.show();
}
result(data);
});
evaluatorResult.done(currentDeferred.resolve);
} else // Sync
result(evaluatorResult);
});
return result;
}
我的调用函数是
self.currentRevenue = asyncComputed(function () {
self.currentRevenueinProgress(true);
var duration = self.duration();
var location = self.location();
return $.ajax({
url: getCurrentTotalRevenue,
type: "GET",
data: { "durationType": duration, "storeId": location }
}).done(function (result) {
self.currentRevenueinProgress(false);
if (result.hasOwnProperty("HasFailed") == true) {
self.currentRevenueError(true);
}else{alert('success');}
});
我正在使用asycComputed函数进行ajax调用,如果任何ajax调用异常所有ajax调用失败并导致页面的html响应。 我可以在这里使用过滤器请建议
答案 0 :(得分:0)
您可以在服务器上编写自定义操作过滤器,捕获异常并将其更改为JSON响应。
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
然后您只需将自定义属性添加到控制器操作中。