Lost
Lost

Reputation: 13585

How to return 302 redirect from Web service environment

I am in a restful service environment and we are using ServiceStack as our service Framework. At this moment, I need to do a redirect directly from the service and as soon as I try to do it from my Get method it fails because I think my Get function looks somethinglike this:

  public override object OnGet(ShareDTO request)
        {               
           HttpContext.Current.Response.Redirect(@"http://www.google.com");
            return new object();
        }

May be because first it is trying to redirect and then it is trying to return a value but this is just wild guess. I am not sure if it is even possible in service environment because all the time whenever I have used Response.Redirect, it was always always a .NET aspx page and never tried in service environment.

Any thoughts?

Upvotes: 3

Views: 3006

Answers (1)

mythz
mythz

Reputation: 143319

The easiest way is to just return a custom HttpResult, e.g:

public object Any(Request request)
{
    return HttpResult.Redirect("http://www.google.com");
}

Which is equivalent to the more explicit:

return new HttpResult
{
    StatusCode = HttpStatusCode.Found,
    Headers =
    {
        { HttpHeaders.Location, "http://www.google.com" },
    }
};

Alternatively you can write directly to the Response, either in a Request Filter or within a Service, e.g:

public object Any(Request request)
{
    base.Response.StatusCode = 302;
    base.Response.AddHeader(HttpHeaders.Location, "");
    base.Response.EndRequest();
    return null;
}

Upvotes: 8

Related Questions