How to return 302 redirect from Web service environment
c#, servicestack, web, web-services
Solution
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;
}
Problem
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?