Filters are a great, often underutilized feature of ASP.NET MVC and ASP.NET Core MVC. They provide a way to hook into MVC’s action invocation pipeline, which makes them great for pulling common, repetitive tasks out of your actions, as Steve Smith explains.
Read this article in the August issue of MSDN Magazine
But aren't you doubling your SQL Server traffic in the GETter? One query in the filter (ListAsync), and a second query in the body of the controller (GetByIdAsync)?
I'm all for making code more readable, but when it doubles your most-expensive operation, you've cleaned up the GETter (one instance), at the expense of the users (every GET for the lifetime of the app).
I like your use of the action filter ValidateAuthorExists. Is there a way to abstract this class? Is something like [ValidateRecordExists(typeof(Author))] possible? In my case I am not using a repository, but an injected DbContext with something like DbSet<Author> Authors.
Off the top of my head, it should be possible with reflection. Might there be a better way?
- Edited by Rhyek Sunday, January 15, 2017 10:43 AM
Great article. I now understand them much better.
WARNING: The code sample is now for VS17! You need to go back a version or two to get the VS15 version of the sample!
One problem hindering better understanding; the source code will not load in my VS for some reason; I don't think its a .NET Core versioning issue. Never seen this one before.
Microsoft Visual Studio Enterprise 2015
Version 14.0.25431.01 Update 3
Microsoft .NET Framework
Microsoft .NET Core Tools (Preview 2) 14.1.21111.0
Microsoft .NET Core Tools (Preview 2)
error : The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the <Project> element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.
I hope this helps
- Edited by EvilCodeMonkey Thursday, February 23, 2017 11:36 AM