如何在Google Cloud App Engine上重写URL?

时间:2018-09-05 10:54:26

标签: reactjs google-app-engine url-rewriting .net-core react-router

我在相同的服务和版本的Google Cloud App Engine上部署了客户端react应用和点网核心API。这是我第一次使用App Engine。通常,当我在IIS上部署时,我将具有一个Web配置,以使用响应路由重写Url,但似乎URL重写不适用于App Engine。有没有其他方法可以使我通过IIS达到相同的结果?

2 个答案:

答案 0 :(得分:2)

欢迎使用App Engine。 Google Cloud App Engine Flex不运行IIS,因此不会读取web.config的内容。

我发现了这篇关于重写ASP.NET Core中间件的文章: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-2.1&tabs=aspnetcore2x 我相信这种中间件可以让您根据需要重写网址,但是如果没有web.config,我不确定。

使用重写中间件而不是web.config的应用程序在IIS和App Engine上的行为相同。

答案 1 :(得分:1)

如果您使用ASP.NET Core,也许可以尝试这种方法?

添加此类:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Rewrite;
using System;

namespace APA.Web.Common
{
    public class RedirectToWwwRule : IRule
    {
        public virtual void ApplyRule(RewriteContext context)
        {
            var req = context.HttpContext.Request;
            if (req.Host.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase))
            {
                context.Result = RuleResult.ContinueRules;
                return;
            }

            if (req.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
            {
                context.Result = RuleResult.ContinueRules;
                return;
            }

            var wwwHost = new HostString($"www.{req.Host.Value}");
            var newUrl = UriHelper.BuildAbsolute(req.Scheme, wwwHost, req.PathBase, req.Path, req.QueryString);
            var response = context.HttpContext.Response;
            response.StatusCode = 301;
            response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Location] = newUrl;
            context.Result = RuleResult.EndResponse;
        }
    }
}

,然后在Startup.cs的“配置方法”中使用它。

添加此代码以使用它:

using Microsoft.AspNetCore.Rewrite;   



public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      ...
      ...

    var options = new RewriteOptions();
    options.AddRedirectToHttps();
    options.Rules.Add(new RedirectToWwwRule());
    app.UseRewriter(options);
...

我正在使用此代码将所有非www / HTTP流量重定向到www / HTTPS版本。