How to find a Service from ServiceStack RequestFilter

I am trying to implement RequestFilter

which conditionally executes based on the information in Service

to be called. I would like to do a RequestFilter

find Service

, look at it for a method / interface / attribute, and conditionally do my job based on that.

I know you can declare RequestFilterAttribute

in Service

, but I couldn't find a good way to make it conditional. I wanted to pass a delegate / lambda to an attribute, but C # doesn't allow that. I could have plugged the type or type name in there, allowing the RequestFilterAttribute

class / method to be found Service

, but seemed to be prone to copy / paste errors.

So, I am left with a little to learn about RequestFilter

or RequestFilterAttribute

to find out about Service

which is in effect (or declared) and then wants to find a method inside Service

that will provide the logic needed to turn the filter code on / off. I couldn't tell if some feature of the IoC container suggested, or if there is some other way to do it, or not.

And then, based on how the filter is being executed, you might want to return your own data, blocking the Service from actually executing. Is it possible? (Is this for the answer?)

+1


source to share


1 answer


This seems to be the key:

var serviceType = EndpointHost.Metadata.GetServiceTypeByRequest(requestDto.GetType());

      

Returns the type of service that will process the request. It's not an instance (but I doubt the service has been instantiated yet), so in order to execute the conditional logic, I had to define a static method and then watch it. I used reflection to find a method that declares a custom attribute and would need to optimize it for better performance.



From there I can conditionally determine if some logic should be run. I can also bypass the service call if I like and return a success response like this:

var successResponse = DtoUtils.CreateSuccessResponse(successMessage);
var responseDto = DtoUtils.CreateResponseDto(requestDto, successResponse);
var contentType = req.ResponseContentType;
res.ContentType = contentType;
res.WriteToResponse(req, responseDto);
// this is the proper way to close the request; you can use Close() but it won't write out global headers
res.EndServiceStackRequest();
return;

      

Or I can create an error response, or I can just go back from RequestFilter

and let the service run fine.

+3


source







All Articles