Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack Global Request Filter Not Firing

Tags:

servicestack

I have a global request filter for authentication as suggested by mythz (ServiceStack dev), in this SO Answer

My filter:

RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
    if (!PublicRoutes.Contains(httpReq.PathInfo))
    {
        new AuthenticateAttribute().Execute(httpReq, httpResp, requestDto);
    }
});

The filter does not fire for me when I request ServiceStack Razor pages that inherit dynamic ViewPage

Example /Default.cshtml:

@inherits ViewPage
<!DOCTYPE html>
<html>
    <head>
        <title>HOME</title>
...
...
ETC

Down the bottom of the answer, in the comments, the question raiser suggests similar behaviour, but does not accurately describe how to reproduce, so I cannot see a solution.

Is there a solution? Did I do something incorrect?


UPDATE

I've discovered I can declare attributes on my page directly:

@using ServiceStack.ServiceInterface
@inherits ViewPage

@{
    new AuthenticateAttribute().Execute(Request, Response, this);
}
<!DOCTYPE html>
...
...
ETC

Or I'm sure I could create a class inherit ViewPage and run them in its Init method and use the new class on the Razor pages.

Both of those solutions seem extraneous and not very DRY, though.

like image 704
Tyst Avatar asked Jan 13 '13 15:01

Tyst


1 Answers

I ended up creating my own ViewPage class to achieve this and invoking the filters after the model has been set on the page:

public abstract class FilterViewPage<TModel> : ViewPage<TModel>
    where TModel : class
{
    public override void SetModel(object o)
    {
        base.SetModel(o);

        this.AppHost.RequestFilters.ForEach(action => action.Invoke(this.Request, this.Response, this.Model));
        this.AppHost.ResponseFilters.ForEach(action => action.Invoke(this.Request, this.Response, this.Model));
    }
}

I ensure only top-level pages inherit this, rather than applying it to partials so the filters only fire once.

like image 138
Tyst Avatar answered Nov 07 '22 21:11

Tyst