【问题标题】:Serving static files with Asp.net 5 against Angular SPA使用 Asp.net 5 针对 Angular SPA 提供静态文件
【发布时间】:2017-02-11 21:15:40
【问题描述】:

我使用 Angular 和 Asp.net 5 创建了 SPA。所有假设为 Angular 路由路径的路由都将返回 index.html,然后 Anguar 将进一步处理路由。

当我在浏览器 url 中输入:http://localhost:12599/user 并按下回车键。创建页面,正确请求所有静态内容。 http://localhost:12599/js/app.js 一切正常。

直到...我想要更复杂的路线,例如:http://localhost:12599/user/registration。我的 index.html 已正确加载,但该死的所有静态内容都被错误地调用,如下所示:http://localhost:12599/user/js/app.js。这显然是行不通的(404),因为附加部分 /user 的东西被剥离了 /registration

有没有一种干净的方法来处理这个问题。或者我在处理静态内容时必须在中间件中做一些肮脏的工作?

像这样:

IF path.Contains("/js") THEN path = path.stripOutEverythingBefore("/js")

所以这会将http://localhost:12599/user/js/app.js 转换为http://localhost:12599/js/app.js

我的一些设置代码,所以这对你们来说不会那么枯燥:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) //, IRouteBuilder routes
{
    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Use(async (context, next) =>
    {
        await next();

        if (context.Request.Path.ToString().Contains("index.html") ||
            SinglePageAppRequestCheck(context))
        {
            // add config cookie
            var webConfig = new WebConfigModel();
            Configuration.Bind(webConfig);
            var jsonSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            context.Response.Cookies.Append("ldmeConfig", JsonConvert.SerializeObject(webConfig, Formatting.None, jsonSettings));
        }

        // If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
        // Rewrite request to use app root
        if (SinglePageAppRequestCheck(context))
        {
            context.Request.Path = "/index.html";
            await next();
        }
    });

    app.UseStaticFiles();
}

private static bool SinglePageAppRequestCheck(HttpContext context)
{
    return context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value);
}

设置取自http://benjii.me/2016/01/angular2-routing-with-asp-net-core-1/

【问题讨论】:

  • 我见过的大多数示例都使用 UrlRewrite。 stackoverflow.com/questions/39651245/…
  • 将尝试在 IIS 中进行设置。但我担心的是这是一个普遍的问题吗?当我在其他框架(南希)中制作网络应用程序时,情况也是如此......我觉得我做错了什么

标签: asp.net angularjs asp.net-core single-page-application static-content


【解决方案1】:

只需将基本链接添加到您的索引,所有相关请求都会正确完成

<base href="/">

我就知道,就是这么简单……不过我花了 3 天时间才弄明白 :)

【讨论】:

  • 你救了我。谢谢
猜你喜欢
  • 2017-08-25
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
相关资源
最近更新 更多