简体   繁体   中英

How can existing ASP.NET core middleware be extended?

I would like to inherit from StaticFileMiddleware (the "standard" way of serving static files, initialized with app.UseStaticFiles() in Startup.cs). The code compiles, but when I try to run it, I get an InvalidOperationException ("InvalidOperationException: Multiple public 'Invoke' or 'InvokeAsync' methods are available.").

These are the essential parts of the code:

public class MyStaticFileMiddleware : StaticFileMiddleware
{
    ...
    public new async Task Invoke(HttpContext context) 
    {
        ...
        await base.Invoke(context);
        ...
    }
    ...
}

Background: I want to introduce meaningful file names for certain static files without changing the actual file names in the file system (like "tree-in-a-meadow.jpg" for an existing file "123.jpg"). So MyStaticFileMiddleware should check the validity of the speaking file name and - if valid - simply execute the existing code of StaticFileMiddleware to serve the file. I would welcome this procedure so that I would not have to reprogram essential parts of StaticFileMiddleware (SRP/KISS).

I have two questions:

  1. Since StaticFileMiddleware.Invoke() was not marked as "virtual", I assume that this procedure is not really intended. But still I don't understand why - purely technically - this procedure doesn't work. Since I use the "new" modifier to explicitly hide the Invoke() method of the base class (StaticFileMiddleware), shouldn't there only one but not "Multiple public 'Invoke' or 'InvokeAsync' methods"?

  2. What is the "intended" way to extend existing middleware accordingly? Should I simply "new StaticFileMiddleware" in my code? How could I inject StaticFileMiddleware into MyStaticFileMiddleware to benefit from Dependency Injection in that case?

Thanks very much for your help!

As i understand middleware visiting your extensions to include additional behaviour in pipeline. To implement different behaviour you should implement it on your own, so extension should hide implementation details. about pipeline

StaticFileMiddleware itself is a wrapper for StaticFileContext, so maybe you need make a new one in same manner StaticFileMiddleware sources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM