Web API redirect to view with model

2019-09-03 16:15发布

问题:

How can I redirect from api method to some View with some model? This is as in the standart controller:

return RedirectToAction("View",model).

Can I make something like this in a method of ApiController?

回答1:

You usually invoke Web API using AJAX. For example using jQuery $.getJSON.

All the AJAX request are handled by the XMLHttpRequest object of the browser. If this object receives a redirect response, it simply repeats the AJAX call to the given URL. That happens trasnparently, i.e. the XHR object doesn't notify in any way that it has done a redirect, so you cannot detect it in any way.

So, the short answer is that you cannot provoke a redirect in the browser via an AJAX call: it doesn't matter if it's Web API or MVC or traditional Web Forms, the problem is always that the XHR hides the redirects response, it simply uses it internally.

The long answer is that you can send an special response to the client, for example an object that can be recognized in the JavaScript AJAX client and use the traditional window.location.href=*newUrl* to force the redirect on the client.

For example you could implement a Web API method like this

public object GetRedirection()
{
   return new {
     redirect = true,
     newUrl = 'http://www.stackoverflow.com'
   };
}

And then invoke it and check the result, for example in this way:

$.getJSON('http://..../MyControler').done(function(result) {
  if (result.redirect) {
    window.location.href = result.newUrl;
  }
})

This is the only way to force a redirect with an AJAX client, i.e. indirectly.

NOTE: of course, if you type the URL of the Web API in the browser address bar, and the invoked action returns a redirect response, it will redirect the browser. But I do suppose that you're using Web API with AJAX. You could also do a strange thing: use the same window.location.href code to invoke the Web API action that returnt the redirect.