Skip to content

Request and response filters

mythz edited this page Mar 13, 2012 · 4 revisions

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:

	    //Add a request filter to check if the user has a session initialized
	    this.RequestFilters.Add((httpReq, httpResp, requestDto) =>
	    {
			var sessionId = httpReq.GetCookieValue("user-session");
			if (sessionId == null)
			{
				httpResp.ReturnAuthRequired();
			}
	    });
	    //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));
			}
	    });

Tip: If you're writing your own response to the response stream inside the response filter, add res.Close(); to signal to ServiceStack not to do anymore processing for this request.

Clone this wiki locally