.net core3.1下接口发布成https协议操作步骤

本文介绍了在ASP.NET Core应用中如何配置HTTPS重定向,以及在Linux上发布时遇到的证书错误。通过在Startup.cs中添加代码实现重定向,并展示了在Linux环境下发布的具体步骤。当启动服务时,由于缺少证书导致Kestrel无法启动,通过运行'dotnet dev-certs https'命令生成并信任开发者证书解决了问题。最终,成功访问到发布的HTTPS接口页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在Startup.cs页面下,ConfigureServices方法里增加如下代码:

public void ConfigureServices(IServiceCollection services)
        {

.......

services.AddHttpsRedirection(InitHttpsRedirectionOptions);

.......

        }


        /// <summary>
        /// 初始化重定向参数
        /// </summary>
        /// <param name="httpsRedirectionOptions"></param>
        public static void InitHttpsRedirectionOptions(HttpsRedirectionOptions httpsRedirectionOptions)
        {
            httpsRedirectionOptions.RedirectStatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status307TemporaryRedirect;
            httpsRedirectionOptions.HttpsPort = 5001;
        }

    /// <summary>
        /// 配置
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

          .......

         }

2、在linux上发布时,进行如下配置

3、在启动服务时,会报如下的错误:

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
crit: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to start Kestrel.
System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date.
To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.

4、执行语名:dotnet dev-certs https,如下图所示:

 5、在浏览器里输入相应的地址https://xx.xx.xx.xx:8889/swagger,即可访问发布后的https接口页面。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值