Dunken
Dunken

Reputation: 8681

REST API: is a redirect (303) a good idea

In my RESTful API I return a redirect (303) in some special cases (e.g. an internal subscription is expired; I know this doesn't sound REST). In order to test my API I wrote a simple webpage using jQuery. However, in case I get a 303 it seems like the browser (XHR?) takes care of the redirect itself and GETs the new resource. As this is hidden from the Ajax call it gets just a 200 at the end. Of course this is misleading as the original call didn't succeed! Obviously this is not what I had in mind: I wanted my client-script to know it has to do something different (-> GET another resource).

Now I'm asking myself whether it's a good idea to even return a 303? Instead I could return a simple 4xx and leave the client on its own.... (probably starting from scratch)

$.ajax({
url: self.links()[0].href,
type: "POST",
statusCode: {
    200: function () {
        //I always ended up here
    },
    303: function () {
    }
},
complete: function (e, xhr, settings) {
    if (e.status === 200) {
        //..and then here
    } else if (e.status === 303) {
    } else {                           
    }
}

Upvotes: 0

Views: 3829

Answers (2)

Michael Freidgeim
Michael Freidgeim

Reputation: 28435

The answer is a bit late :), but I had to research it myself.

API should return 401 Not Authorized, but web page should return 302/303 Redirect  From https://aspnet.uservoice.com/forums/147201-asp-net-web-api/suggestions/2856315-add-option-to-return-401-not-authorized-instead-of And   ASP.NET Web API : Correct way to return a 401/unauthorised response

  The HTTP response status code 302 Found is a common way of performing URL redirection. An HTTP response with this status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field. From https://restfulapi.net/http-status-codes/.

In other  words, if javascript make ajax call and receives 302, it will do another ajax call to a new location, but will not redirect the whole page to a new URL    ASP.NET Web API : Correct way to return a 401/unauthorised response

Another related discussion is in ASP.Net 5 (vNext) Web API unauthorized requests returns 302 redirect response instead of 401

Upvotes: 0

MaX
MaX

Reputation: 1805

jQuery $.ajax always follows redirects. I'm afraid it can't be disabled.

Returning redirect as response to XHR request

How to prevent jQuery ajax from following a redirect after a post?

Upvotes: 1

Related Questions