如何让 LetsEncrypt 在 ASP.Net Core Razor Pages 中工作?

Rob*_*Rob 3 lets-encrypt asp.net-core-2.0 razor-pages

我如何让 ASP.Net Core Razor 页面符合 letencrypt.com 对“握手”的要求?我曾尝试使用适用于 MVC 的解决方案,但路由的完成方式在 Razor Pages 中不起作用。

Rob*_*Rob 5

我从 Royal Jay 网站上的这个优秀教程开始。向 Web 应用程序添加路由是我的解决方案与普通 MVC 应用程序不同的地方。由于您必须每 3 个月获得一次新的 SSL 证书,因此我将此解决方案进行了配置,以便最终更改密钥非常容易。

在我的appsettings.json文件中,我为 LetsEncrypt 添加了以下条目:

"LetsEncrypt": {
    "Key": "the entire key from your letsencrypt initial session goes here"
  }
Run Code Online (Sandbox Code Playgroud)

此处的条目是您从letsencrypt-auto可执行文件收到的整个密钥(这是Royal Jay 教程中第二个红色下划线部分)。

为了将配置属性传递到将处理来自 LetsEncrypt 的握手的页面,我创建了一个新接口和一个小类来保存密钥:

界面:

using System;
using System.Collections.Generic;
using System.Text;

namespace Main.Interfaces
{
    public interface ILetsEncryptKey
    {
        string GetKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

班级:

using Main.Interfaces;

namespace Main.Models
{
    public class LetsEncryptKey : ILetsEncryptKey
    {
        private readonly string _key;

        public LetsEncryptKey(string key) => _key = key;

        public string GetKey() => _key;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在startup.cs文件中,我将这些行添加到ConfigureServices部分:

    var letsEncryptInitialKey = Configuration["LetsEncrypt:Key"];

    services.AddMvc().AddRazorPagesOptions(options =>
    {
        options.Conventions.AddPageRoute("/LetsEncrypt", $".well-known/acme-challenge/{letsEncryptInitialKey.Split('.')[0]}");
    });

    services.AddSingleton<ILetsEncryptKey>(l => new LetsEncryptKey(letsEncryptInitialKey));
Run Code Online (Sandbox Code Playgroud)

现在我们唯一要做的就是创建将处理握手请求并返回响应的页面。

LetsEncrypt.cshtml.cs:

using Main.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPages.Pages
{
    public class LetsEncryptModel : PageModel
    {
        private readonly ILetsEncryptKey _letsEncryptKey;

        public LetsEncryptModel(ILetsEncryptKey letsEncryptKey)
        {
            _letsEncryptKey = letsEncryptKey;
        }

        public ContentResult OnGet()
        {
            var result = new ContentResult
            {
                ContentType = "text/plain",
                Content = _letsEncryptKey.GetKey()
            };

            return result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)