[英]Handling 404 Not Found for WebApi
I am creating an 我正在创建一个
Asp.Net MVC + AngularJS
Asp.Net MVC + AngularJS
application. 应用。 Within a WebApi Controller, I have handled any sort of exception (500, 404 etc).
在WebApi控制器中,我已经处理了各种异常(500、404等)。 On the other hand, all unhandled exceptions get caught in
另一方面,所有未处理的异常都被捕获
Global.asax.cs
的Global.asax.cs
file's 文件的
Application_Error
应用程序错误
method. 方法。 However, if a whole API is missing from the application, it shows the 404 error on the browser's console as expected, but I need to redirect to a proper UI (html/cshtml) in this case too.
但是,如果应用程序缺少整个API,则会按预期在浏览器的控制台上显示404错误,但是在这种情况下,我也需要重定向到适当的UI(html / cshtml)。 How can I handle this type of exceptions?
如何处理此类异常?
PS I have tried using the PS我尝试使用
customErrors
的customErrors
property in the 物业
Web.config
Web.config文件
file too, but it was in vain. 文件,但它是徒劳的。
You need to follow the following steps, 您需要执行以下步骤,
Please follow This awesome tutorial, written by Imran Baloch for detailed information 请关注Imran Baloch撰写的本教程,以获取详细信息
Here are some ways on how you can handle API errors to perform a redirect. 以下是一些有关如何处理API错误以执行重定向的方法。
Using jQuery.ajaxError() . 使用jQuery.ajaxError() 。
$(document)
.ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == 404) {
window.location.replace("http://www.stackoverflow.com");
}
});
Using jQuery.ajaxSetup() . 使用jQuery.ajaxSetup() 。
$.ajaxSetup({
global: true,
error: function(xhr, status, err) {
if (xhr.status == 404) {
window.location.replace("http://www.stackoverflow.com");
}
}
});
If you want the angular way you can utilize [Javascript] Global Ajax error handler with AngularJS . 如果您想要有角度的方法,则可以将[Javascript] Global Ajax错误处理程序与AngularJS结合使用 。
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'response': function(response) {
// do something on success
return response || $q.when(response);
},
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise;
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
angular.module("globalErrors", ['appStateModule']).factory "myHttpInterceptor", ($q, $log, growl) ->
response: (response) ->
$log.debug "success with status #{response.status}"
response || $q.when response
responseError: (rejection) ->
$log.debug "error with status #{rejection.status} and data: #{rejection.data['message']}"
switch rejection.status
when 404
window.location.replace("http://www.stackoverflow.com");
else
console.log(rejection.status);
# do something on error
$q.reject rejection
.config ($provide, $httpProvider) ->
$httpProvider.interceptors.push('myHttpInterceptor')
This is based on AngularJS 1.1.4. 这基于AngularJS 1.1.4。 You can apply similar strategy if you're using a different version.
如果您使用的是其他版本,则可以应用类似的策略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.