asp.net - 包装 StaticFileMiddleware 以重定向 404 错误

标签 asp.net angularjs owin

我正在尝试将自定义中间件注入(inject)到我的 OWIN 管道中,该管道包含 StaticFileMiddleware可从 MS 获得,以便在 AngularJS 中支持 HTML 5 模式。我一直在关注本指南:http://geekswithblogs.net/shaunxu/archive/2014/06/10/host-angularjs-html5mode-in-asp.net-vnext.aspx

根据我所能收集到的关于它应该如何工作的信息,我的中间件正在将请求传递给静态文件中间件,然后如果它无法解决这些请求(即对 HTML 5 Angular 路径的请求,“/whatever "),而是返回基本的 Angular 页面,以便对 HTML 5 路径的硬请求将起作用。

我的问题是调用内部中间件的结果似乎总是一个 200 状态码,即使在我的浏览器中我得到一个 404,这让我摸不着头脑。这是我的代码供引用:

public static class AngularServerExtension
{
    public static IAppBuilder UseAngularServer(this IAppBuilder builder, string rootPath, string entryPath)
    {
        var options = new AngularServerOptions()
        {
            FileServerOptions = new FileServerOptions()
            {
                EnableDirectoryBrowsing = false,
                FileSystem = new PhysicalFileSystem(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootPath))
            },
            EntryPath = new PathString(entryPath)
        };

        builder.UseDefaultFiles(options.FileServerOptions.DefaultFilesOptions);
        return builder.Use(new Func<AppFunc, AppFunc>(next => new AngularServerMiddleware(next, options).Invoke));           
    }
}

public class AngularServerMiddleware
{
    private readonly AngularServerOptions _options;
    private readonly AppFunc _next;
    private readonly StaticFileMiddleware _innerMiddleware;

    public AngularServerMiddleware(AppFunc next, AngularServerOptions options)
    {
        _next = next;
        _options = options;

        _innerMiddleware = new StaticFileMiddleware(_next, options.FileServerOptions.StaticFileOptions);
    }

    public async Task Invoke(IDictionary<string, object> environment)
    {
        IOwinContext context = new OwinContext(environment);
        // try to resolve the request with default static file middleware
        await _innerMiddleware.Invoke(environment);
        Debug.WriteLine(context.Request.Path + ": " + context.Response.StatusCode);
        // *** Right here is where I would expect a 404 but I get a 200 when debugging,
        // even though my browser eventually returns a 404

        // route to root path if the status code is 404
        // and need support angular html5mode
        if (context.Response.StatusCode == 404 && _options.Html5Mode)
        {
            context.Request.Path = _options.EntryPath;
            await _innerMiddleware.Invoke(environment);
            Console.WriteLine(">> " + context.Request.Path + ": " + context.Response.StatusCode);
        }
    }
}
public class AngularServerOptions
{
    public FileServerOptions FileServerOptions { get; set; }

    public PathString EntryPath { get; set; }

    public bool Html5Mode
    {
        get
        {
            return EntryPath.HasValue;
        }
    }

    public AngularServerOptions()
    {
        FileServerOptions = new FileServerOptions();
        EntryPath = PathString.Empty;
    }
}

最佳答案

我不想被绑定(bind)到 IIS,随着 asp.net core 的发展。以下是我使用 OWIN 使其工作的方法:

// catch all for html5/angular2 client routing urls that need to be redirected back to index.html
// for original, see: http://stackoverflow.com/questions/27036448/how-to-intercept-404-using-owin-middleware/30741479#30741479
app.Use(async (ctx, next) =>
{
    // execute the rest of the pipeline
    //  though really, we're last in this configuration
    //  but, this allows the other static file handlers
    //  and web api route handlers to fail
    await next();

    // double check that we have a 404
    //  we could also double check that we didn't request a file (with an extension of some sort)
    if (ctx.Response.StatusCode != 404)
    {
        return;
    }

    // we have a 404, serve our default index.html
    var middleware = new StaticFileMiddleware(
        env => next(), new StaticFileOptions
        {
            FileSystem = new PhysicalFileSystem("./wwwroot"),
            RequestPath = PathString.Empty
        });

    ctx.Request.Path = new PathString("/index.html");
    await middleware.Invoke(ctx.Environment);
});

我需要调用 next()在我检查状态码之前,因为我假设其他中间件不会设置 404,直到所有中间件都有机会处理它。

免责声明:我才刚刚开始探索基于 OWIN 的托管,因此虽然这似乎可行,但可能存在一些非最佳实践。

关于asp.net - 包装 StaticFileMiddleware 以重定向 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25916851/

相关文章:

c# - 具有多个模板的 ASP Repeater 控件

javascript - 在 IE 中以编程方式隐藏弹出窗口

asp.net - WsFederation 身份验证登录循环

asp.net - Web Api Asp.Net 身份

c# - 为什么要使用 Using block 连接到 EntityFramework 模型?

asp.net - 默认情况下分配给下拉列表的 aspNetDisabled 类

node.js - Angular 错误的原因 : "Error: No module: ngCookies"?

Angularjs e2e 测试过去/ future 的比较

javascript - 使用 moment.js 按 'last month' 和 'last week' 过滤点击时的对象数组

c# - Mono 上的 SignalR 和 Websockets