简体   繁体   中英

ASP.NET OWIN Middleware - modify HTTP response

I need to intercept all the aspx and js file requests and to replace some text labels if they are present. This middleware should work as an IIS module, obviously without interfering with the normal flow of the web application. I wrote some code but I have no idea how to do it.

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use(typeof(FilterMiddleware), Console.Out);
    }
}

public class FilterMiddleware : OwinMiddleware
{
    private readonly TextWriter logger;
    private readonly OwinMiddleware nextMiddleware;

    public FilterMiddleware(OwinMiddleware nextMiddleware, TextWriter logger) : base(nextMiddleware)
    {
        this.nextMiddleware = nextMiddleware;
        this.logger = logger;
    }

    public override async Task Invoke(IOwinContext context)
    {
        var headers = context.Request.Headers;

        // IF .js OR .ASPX REPLACE TEXT HERE //

        await nextMiddleware.Invoke(context);
    }
}

I think what you are looking for is

if (context.Request.ContentType = "application/json") // or whatever MIME type
{
   ...
}

Then once you do all your processing, don't forget to create a response back

context.Response.ContentType = "application/json";
string result = ""; // whatever string you are sending back
await context.Response.WriteAsync(result);

However, if it snags some kind of error, such as an unsupported method (ie PUT)

context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
await context.Response.WriteAsync(String.Empty);

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