I'm trying the following:
[System.Web.Http.AcceptVerbs("PUT")]
public HttpResponseMessage MakePost(PostDto post) {
try {
var response = Request.CreateResponse(HttpStatusCode.Redirect); // tried MOVED too
response.Headers.Location = new Uri("google.com");
return response;
} catch (Exception e) {
ErrorSignal.FromCurrentContext().Raise(e);
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
Which seems to be partially working - when this is called, I see the POST request in chrome debugger. Nothing appears in the Response tab, but then I see a GET request sent to the new URI, yet the page never changes, and my AJAX call throws an error:
var options = {
url: postUrl,
type: type,
dataType: 'json',
xhrFields: {
withCredentials: true
}
};
return $.ajax(options)
.done(function (response) {
// do stuff
})
.fail(function (response) {
alert('error) // this gets hit - shouldn't the browser have redirected at this point?
}).complete(function () {
// stuff
});
};
If I inspect response, I see a Status 200 "OK".... I'm so confused.
What am I doing wrong?
This happens because the code issuing the AJAX request follows the redirect, not the browser. This will then fail because the AJAX request tries to access a different domain. If you want to redirect the browser, you should return some JSON result or a custom HTTP header, manually pick this up in your jQuery, and do the redirect there.
In your controller:
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("FORCE_REDIRECT", "http://google.com");
Then add a success callback to your AJAX call:
success: function(data, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('FORCE_REDIRECT') !== null){
window.location = jqXHR.getResponseHeader('FORCE_REDIRECT');
return;
}
}
In the past, I've wrapped the controller result up in a custom action result class for reuse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With