Richard B. Sorensen
Richard B. Sorensen

Reputation: 111

ServiceStack - How to return ResponseDTO from RequestFilter?

I am using a RequestFilter for pre-processing some of the messages to a web service, and if there are errors I want to return a ResponseDTO, and then kill further processing on the request. How can I achieve that functionality?

Also, I am implementing this by using the [RequestFilter] decorator on the RequestDTO class. If I want to have multiple request filters, how can I select the filter to be used for a given RequestDTO?

Upvotes: 1

Views: 502

Answers (2)

Todd
Todd

Reputation: 520

The above answer tells how to select filters and how to fail, but not how to return a successful alternative response. How to find Service from ServiceStack RequestFilter shows how to create an appropriate ResponseDTO. The key there is that you serialize the ResponseDTO to the response stream and then close the stream. I guess ServiceStack uses this as a cue not to run the Service or any other filters.

Upvotes: 1

paaschpa
paaschpa

Reputation: 4816

if there are errors I want to return a ResponseDTO, and then kill further processing on the request. How can I achieve that functionality? Not exactly sure how you'll determine errors so this is a pretty basic solution.

public class RequestFilterAttribute : Attribute, IHasRequestFilter
{
    public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
    {
        if(requestDto.GetType() == typeof(YourRequestType))
        {
            //code to check for errors - if error throw exception 
            throw new Exception("Exception for your request type");
        }
    }
}

If I want to have multiple request filters, how can I select the filter to be used for a given RequestDTO?

You can create several different RequestFilter implementations and decorate each of your DTOs with the different implementations.

public class FilterOneAttribute : Attribute, IHasRequestFilter
{
    //Code
}

public class FilterTwoAttribute : Attribute, IHasRequestFilter
{
    //Code
}

[FilterOne]
public class OneClass 
{
    //Code
}

[FilterTwo]
public class TwoClass
{
    //Code
}

Upvotes: 2

Related Questions