ASP.NET OWIN中间件-修改HTTP响应

时间:2019-01-14 10:46:15

标签: c# asp.net owin

我需要拦截所有 aspx js 文件请求,并替换一些文本标签(如果有)存在。该中间件应作为IIS模块工作,显然不会干扰Web应用程序的正常流程。 我写了一些代码,但我不知道该怎么做。

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

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找的是

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

然后,一旦您完成所有处理,别忘了创建回复

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

但是,如果遇到某种错误,例如不支持的方法(例如PUT)

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