gpt4 book ai didi

asp.net-core - 在一个 Controller 上强制执行 https,在另一个 Controller 上强制执行 http

转载 作者:行者123 更新时间:2023-12-05 05:15:05 25 4
gpt4 key购买 nike

我正在使用 ASP.NET 核心 2.1,我正在寻找一种在一个 Controller 上实现 https 并在另一个 Controller 上实现 http 的方法。

以下文档展示了如何为整个 ASP.NET 核心而非单个 Controller 强制执行 HTTPS。

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

最佳答案

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

[AllowHttp]
public class HomeController : Controller

其中 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
{
}

接下来,全局过滤器:

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

最后,您必须在 Startup.cs 中全局注册过滤器:

services.AddMvc(options =>
{
options.Filters.Add(new RedirectToHttpsActionFilter());
});

我相信您可以通过 URL 重写实现相同的目的,但在您可能更改 Controller 路由的情况下,这将在没有干预的情况下继续工作。

关于asp.net-core - 在一个 Controller 上强制执行 https,在另一个 Controller 上强制执行 http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com