0

I have an query parameter in a number of controller actions that I would like to modify in a number of ways before using it.

e.g.

public async Task<ActionResult<Foo>> GetFoo(string imageName)
{
    imageName = Uri.UnescapeDataString(imageName);
    imageName = RewriteSelfToUserId(imageName); // appends something to the string based on the currently logged in user
    .....
}

I would like to put all of this behaviour in one place, I am just unsure what the best way to do it is.

  1. Using a class - not my favorite because I need some stuff from the request context which I would need to pass in.
  2. Attribute on the string. Probably the same? How can I pass in the current User?

  3. ???

EzLo
  • 13,780
  • 10
  • 33
  • 38
Christian Sauer
  • 10,351
  • 10
  • 53
  • 85

1 Answers1

1

Add a class which inherits from IActionFilter:

public class MyFilter:IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // pre-processing here
        var queryArgs = context.HttpContext.Request.Query;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // post-processing here
    }
}

To register the filter, add this option in your Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(opt => opt.Filters.Add(new MyFilter()))
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

OnActionExecuted will be called before each Action and OnActionExecuting will be called after each Action.

Joshit
  • 1,238
  • 16
  • 38
  • As an additional ressource you can also look at this question: https://stackoverflow.com/questions/50406111/asp-net-core-ways-to-handle-custom-response-output-format-in-web-api/50564534#50564534 – Joshit Feb 04 '19 at 09:35