Question

I am trying to return a ActionResult from an MVC api, and if you give it a redirect uri in the post body it should redirect that uri. Right now if you do not give it a uri it performs fine. But if you give it a uri where it should redirect to that uri it just returns a 302 and does not navigate anywhere.

Now I think one issue I am having is that the returned location in the response header is the base URI for the MVC and then the input URI. One problem I have is that all documentation on this I have found, well sucks.

So my question is how do I use the RedirectResult action to actually redirect to a different URI? Also can I redirect to a URI that is outside the current domain? I am worried I cannot since it is appending the base URI to the location in the response. It does not force the clients browser to navigate to another URI.

Here is my action result.

    [AllowAnonymous]
    public ActionResult Dispatch(Dto.GoogleAnalyticsEvent evt)
    {
        log.DebugFormat("Dispatch()");
        if (evt.Redirect != null)
        {
            return new RedirectResult(evt.Redirect, false);
        }
        else
        {
            return Dispatch<Dto.GoogleAnalyticsEvent>(evt, _api.DispatchAnalyticsEvent, true);
        }
    }

Here is the returned response if you give it a uri in the post body. The response code is actually a 302 found.

Access-Control-Allow-Head...    Content-Type
Access-Control-Allow-Meth...    GET,POST
Cache-Control   private
Content-Length  139
Content-Type    text/html; charset=utf-8
Date    Wed, 22 May 2013 22:42:25 GMT
Location    /events/www.google.com
Server  Microsoft-IIS/7.5
access-control-allow-orig...    *

Thanks in advance for the help.

Just to clarify, I was looking for the response from the API to force the browser to navigate to a URI upon response. Though now that I type that out loud it seems that browsers probably would not allow that. How is a 302 found supposed to affect the browser?

Was it helpful?

Solution

If you are calling this action via AJAX (or some other form of direct call to server) the browser will have no way to know that server returned 302 (or 40x, 50x, 200 or any other kind of response).

The behavior is exactly the same as if you get 200+data response for AJAX request - browser will not magically navigate to that response page.

Solution: if you need to redirect as result of AJAX request you need to redesign your protocol to return some 200 response that says "please redirect to this Url" and set window.location.href accordingly on client side when you get such response.

Note that AJAX call will follow 302 redirect and result of the call will be page you are redirecting to (if on the same domain) or "access denied" of some sort if it is cross domain and CORS not turned on destination. See How to prevent ajax requests to follow redirects using jQuery for more background on it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top