1

I'm trying to implement a RequestFilter that conditionally executes, based on information in the Service that would get invoked. I'd like to make the RequestFilter find the Service, look at it for a method/interface/attribute, and conditionally do its work based on that.

I'm aware that you can declare a RequestFilterAttribute on the Service, but I couldn't figure out a good way to make it conditional. I wanted to pass a delegate/lambda into the attribute, but C# doesn't allow that. I could have plugged in a Type or type name into there, allowing the RequestFilterAttribute to find the Service class/method, but that seemed prone to copy/paste errors.

So I'm left with wanting some way for a RequestFilter or RequestFilterAttribute to know about the Service it's acting on (or declared on) and then wanting to look up a method inside that Service that would provide the logic needed to enable/disable the filter's code. I couldn't tell if some feature of the IoC container offered this, or if there is some other way to do it, or not.

And then, based on how the filter executes, it might need to return its own data, blocking the Service from actually executing. Is this possible? (Is this the answer for that?)

Community
  • 1
  • 1
Todd
  • 530
  • 4
  • 14

1 Answers1

3

This seems to be the key:

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

This returns the type of the service that will handle the request. It's not an instance (but I am doubtful a service instance has even been created yet) so to do conditional logic I had to define a static method and then look it up. I used reflection to find a method declaring a special attribute, and will need to optimize that for best performance.

From there I can conditionally determine whether to run some logic. I can also bypass calling the service if I like and return a success response as follows:

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 just return from the RequestFilter and let the service execute normally.

Todd
  • 530
  • 4
  • 14