Access the HTTP Request in Web Services
By default ServiceStack provides a clean, dependency-free IService
Advantages for living without it
If you don't need to access the HTTP Request context there is nothing stopping you from having your same IService
Injecting the IRequestContext into your Service
Although working in a clean-room can be ideal ideal from re-usability and testability point of view, you stand the chance of missing out a lot of the features present in HTTP. So not wanting to limit your web services usefulness, this feature of accessing the RequestContext has been present in ServiceStack from early on however because it hasn't been well documented its not very well-known (An issue this wiki page hopes to correct :)
Just like using built-in Funq IOC container, the way to tell ServiceStack to inject the request context is by implementing the IRequiresRequestContext interface which will get the IRequestContext inject before each request.
public interface IRequestContext : IDisposable
{
T Get<T>() where T : class;
string IpAddress { get; }
IDictionary<string, Cookie> Cookies { get; }
EndpointAttributes EndpointAttributes { get; }
IRequestAttributes RequestAttributes { get; }
string MimeType { get; }
string CompressionType { get; }
string AbsoluteUri { get; }
IFile[] Files { get; }
}
This will allow your services to inspect any Cookies or download any Files that were sent with the request. Note: to set Response Cookies or Headers, return the HttpResult object.
Accessing the IHttpRequest and IHttpResponse using filters
A recent addition to ServiceStack is the ability to register custom Request and Response filters. These should be registered in your AppHost.Configure() onload script:
The Request Filters are applied before the service gets called and accepts: (IHttpRequest, IHttpResponse, RequestDto) e.g:
//Add a request filter to check if the user has a session initialized this.RequestFilters.Add((httpReq, httpReq, requestDto) => { var sessionId = httpReq.GetCookieValue("user-session"); if (sessionId == null) { httpReq.ReturnAuthRequired(); } });The Response Filters are applied after your service is called and accepts: (IHttpRequest, IHttpResponse, ResponseDto) e.g:
//Add a response filter to add a 'Content-Disposition' header so browsers treat it as a native .csv file this.ResponseFilters.Add((req, res, dto) => { if (req.ResponseContentType == ContentType.Csv) { res.AddHeader(HttpHeaders.ContentDisposition, string.Format("attachment;filename={0}.csv", req.OperationName)); } });