简体   繁体   中英

Handling 404 Not Found for WebApi

I am creating an

Asp.Net MVC + AngularJS

application. Within a WebApi Controller, I have handled any sort of exception (500, 404 etc). On the other hand, all unhandled exceptions get caught in

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. How can I handle this type of exceptions?

PS I have tried using the

customErrors

property in the

Web.config

file too, but it was in vain.

You need to follow the following steps,

  1. Create a Controller to handle Errors
  2. Configure the route for that error controller
  3. Handle 404 error using custom IHttpControllerSelector.
  4. Pass the request to the above custom IHttpControllerSelector if no matching action method found in the selected controller. this can handle using custom IHttpActionSelector.
  5. Finally, register the custom IHttpControllerSelector and IHttpActionSelector in global.asax.cs file

Please follow This awesome tutorial, written by Imran Baloch for detailed information

Here are some ways on how you can handle API errors to perform a redirect.

Using jQuery.ajaxError() .

$(document)
    .ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
        if (jqXHR.status == 404) {
            window.location.replace("http://www.stackoverflow.com");
        }
    });

Using 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 .

$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. You can apply similar strategy if you're using a different version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM