Filtering Routes in PreRequestFilter

I have a PreRequestFilter that needs to determine if the request is of a certain DTO type.

What would be the best way to detect which DTO is being requested, regardless of the value of any of its fields?

[Route("/stuff/{Id}", "GET")]
public class MyDto: IRetunr<MyDtoResponse>
{
    public string Id { get;set; }
}

I want to detect when the request is for MyDto, regardless of any value (including null) of the Id property

PreRequestFilters happens before the Request DTO has been created so you wont have the Request DTO and its executed for all ServiceStack Requests not just Service requests. You should really be checking for Service Requests in a Global Request Filter or a Typed Request Filter which only gets executed for a specific Request DTO.

But if you need to check for it in PreRequestFilters, the easiest way is something like:

var restPath = RestHandler.FindMatchingRestPath(req, out var contentType);
if (restPath?.RequestType == typeof(MyDto)) {
  //..
}

Note this only checks for custom (i.e. user-defined routes), not Service Requests via pre-defined Routes. You really should be checking for Request DTO requests in Global or Typed Request Filters.

Thanks, in my case its a custom route, so this should be reliable enough for now.

Actually @mythz, I need to go a bit further.

This code cannot be a GlobalRequestFilter because it must run on all requests before any RequestFilters run such as AuthenticationAttribute.

I’m not sure how I can deal with this now, since I need the code to run on every request, and only for this one DTO type, I need that same code to run, but also to take a separate action.

If it’s only for 1 DTO Type create a Request Filter Attribute and add it to the Service with the Request DTO, you can use the Priority to control the order which is run <0 will be run before the Global Request Filters, <-100 will execute before any other Reqeust Filter Attributes like the [Authenticate] Attribute.

Thanks but its not for only one operation, I need the same code to run for every request. This code has two steps: 1) harvest the tenancy id from the URL, 2) validates that tenancy against a whitelist.
For this one operation, I want step 1) to run, but not step 2).

So I need the code to run for all requests, but for this specific one, I omit the 2nd step.

I don’t understand why the code to check for the DTO is insufficient, if it is, do your own checks to inspect the IReqeust params to detect the Request you want to treat differently.

The Order of Operations lists all the filters available throughout the Request Pipeline. Use the PreRequestFilters to add logic you want to run against all ServiceStack Requests whilst you can use the Global Request Filters for logic you want to run against all ServiceStack Service Requests.