如何在mvc6中启用https

How to enable https in mvc6

我是如何尝试做到这一点的:

1- 在启动时设置过滤器:

     public IServiceProvider ConfigureServices(IServiceCollection services)
       {
        //...
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new RequireHttpsAttribute());
        });

2- 在控制器中设置 [RequireHttps]

[RequireHttps]
public class HomeController : BaseController
{
    public ViewResult Index()
    {
        return View();
    }
 }

3-加入project.json

 "kestrel": "Microsoft.AspNet.Hosting --server=Microsoft.AspNet.Server.Kestrel --server.urls=https://localhost:1234"

仍然无法正常工作。 我做错了什么?

编辑: 这是 beta8 中还没有的新功能。在我尝试在 Github 的 beta8 标签中找到此功能后,我注意到了。看来您现在唯一的解决方案是要么在 IIS(支持 HTTPS)之后,要么在 NGINX 之后,同时将为您添加该模块。

确保在您的 Startup.cs/Configure 方法中启用 SSL。

这样做是这样的:

var certPath = "c:\mycert.pfx";
app.UseKestrelHttps(new X509Certificate2(certPath, "certificatePassword"));

动作过滤器将仅作用于实际 URL。您确实需要侦听带有证书的端口才能使用 HTTPS。

希望这对您有所帮助。

Source to sample Startup.cs