Rick
Rick

Reputation: 1072

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);
    }
}

Upvotes: 2

Views: 1809

Answers (1)

Svek
Svek

Reputation: 12868

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);

Upvotes: 2

Related Questions