包装StaticFileMiddleware以重定向404错误

时间:2014-09-18 15:32:36

标签: asp.net angularjs owin

我试图将自定义中间件注入我的OWIN管道,该管道包装了MS提供的StaticFileMiddleware,以支持AngularJS中的HTML 5模式。我一直在关注本指南:http://geekswithblogs.net/shaunxu/archive/2014/06/10/host-angularjs-html5mode-in-asp.net-vnext.aspx

从我可以收集的关于这应该是如何工作的,我的中间件将请求传递给静态文件中间件,然后如果它不能解决这些请求(即,请求HTML 5角度它改为返回基本角度页面,以便对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;
    }
}

2 个答案:

答案 0 :(得分:17)

根据您的问题,我不确定您使用的是IIS还是自我主机。如果您使用的是IIS,那么与使用owin中间件相比,有一个更清洁/更快的解决方案: 您可以使用IIS重写引擎,在Web配置中复制以下内容。

<system.webServer>

<rewrite>
  <rules>
    <!--Redirect selected traffic to index -->
    <rule name="Index Rule" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> 
        <add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" />
      </conditions>
      <action type="Rewrite" url="/index.html" />
    </rule>
  </rules>
</rewrite>
...
</system.webServer>

此行允许正常提供所有文件:

<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> 

此行允许api正常提供

<add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" />

其他所有内容都获得index.html

答案 1 :(得分:3)

我不想被IIS绑定,因为asp.net核心正在向前发展。以下是我使用OWIN进行工作的方法:

a

我在检查状态代码之前需要调用// 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); }); ,因为我假设其他中间件不会设置404,直到所有中间件都有机会处理它。

免责声明:我只是开始探索基于OWIN的托管,所以虽然这似乎有效,但可能会有一些非最佳做法。