在一个控制器上强制使用 https,在另一控制器上强制使用 http

Dro*_*ror 5 asp.net-core asp.net-core-webapi

我正在使用 ASP.NET core 2.1,我正在寻找一种方法来在一个控制器上强制执行https ,在另一个控制器上强制执行http 。

以下文档展示了如何对整个 ASP.NET core 强制执行 HTTPS,但不适用于单个控制器。

https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-2.1&tabs=visual-studio

Joh*_*n H 4

一种方法是使用两个操作过滤器:一个用于强制 HTTPS 重定向,另一个用于允许 HTTP 请求。第一个将在全局注册,第二个仅与您希望允许 HTTP 流量到达的控制器/操作一起使用。举个例子:

[AllowHttp]
public class HomeController : Controller
Run Code Online (Sandbox Code Playgroud)

其中AllowHttp定义为:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
// Inheriting from ActionFilterAttribute allows this to show
// up in the ActionExecutingContext.Filters collection.
// See the global filter's implementation.
public class AllowHttpAttribute : ActionFilterAttribute
{
}
Run Code Online (Sandbox Code Playgroud)

接下来,全局过滤器:

// Needed for the GetEncodedUrl() extension method.
using Microsoft.AspNetCore.Http.Extensions;

public class RedirectToHttpsActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.Filters.Any(x => x is AllowHttpAttribute))
        {
            return;
        }

        if (!context.HttpContext.Request.IsHttps)
        {
            var insecureUri = context.HttpContext.Request.GetEncodedUrl();
            var secureUri = insecureUri.Replace("http://", "https://");

            // As you're likely trying this out locally, you'll need to specify
            // the port to redirect to as well. You won't need this on production.
            // Change the first port to your HTTP port and the second to your HTTPS port.
            secureUri = secureUri.Replace(":49834", ":44329");

            context.Result = new RedirectResult(secureUri);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您必须在以下位置全局注册过滤器Startup.cs

services.AddMvc(options =>
{
    options.Filters.Add(new RedirectToHttpsActionFilter());
});
Run Code Online (Sandbox Code Playgroud)

我确信您可以通过 URL 重写实现相同的目标,但在您可以更改控制器路由的情况下,这将在无需干预的情况下继续工作。