包装 StaticFileMiddleware 以重定向 404 错误 [英] Wrapping StaticFileMiddleware to redirect 404 errors

查看:29
本文介绍了包装 StaticFileMiddleware 以重定向 404 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to inject a custom middleware into my OWIN pipeline that wraps the StaticFileMiddleware available from MS in order to support HTML 5 mode in AngularJS. I've been following this guide: http://geekswithblogs.net/shaunxu/archive/2014/06/10/host-angularjs-html5mode-in-asp.net-vnext.aspx

从我可以收集到的它应该如何工作,我的中间件将请求传递给静态文件中间件,然后如果它无法解析这些请求(即对 HTML 5 角度路径的请求,"/whatever"),而是返回基本角度页面,以便对 HTML 5 路径的硬请求将起作用.

From what I can gather of how this is supposed to work, my middleware is passing along requests to the static file middleware, and then if it can't resolve those requests (i.e., a request for an HTML 5 angular path, "/whatever"), it instead returns the base angular page so that a hard request for an HTML 5 path will work.

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

My problem is that the result of invoking the inner middleware always seems to be a 200 status code, even though in my browser I get a 404, which leaves me scratching my head. Here's my code for reference:

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

推荐答案

根据您的问题,我不确定您使用的是 IIS 还是 selfhost.如果您使用的是 IIS,则有一个比使用 owin 中间件更简洁/更快的解决方案:您可以使用 IIS 重写引擎,将以下内容复制到您的 web 配置中.

From your question I am not sure whether you are using IIS or selfhost. If you are using IIS, there is a much cleaner/faster solution than messing up with owin middleware: You can use IIS rewrite engine, copy the following inside your web config.

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

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

This line allows all files to be served normally:

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

此行允许api正常服务

this line allows the api to be served normally

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

其他一切都得到 index.html

Everything else gets index.html

这篇关于包装 StaticFileMiddleware 以重定向 404 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆