ASP .Net Core创建一个httppost请求并添加证书

ASP .Net Core创建一个httppost请求并添加证书

创建.net Core程序,使用自签名证书,可以处理https的get和post请求。

创建证书

创建自签名证书的流程可以在这里查看:

https://blog.csdn.net/GoodCooking/article/details/139815278

创建完毕后:
在这里插入图片描述

继续输入命令,创建.pfx 证书,

openssl pkcs12 -export -out myNameZhengShu\cert.pfx -inkey myNameZhengShu\key.pem -in myNameZhengShu\cert.pem

在这里插入图片描述输入密码123456,当然是看不到的啦

在这里插入图片描述在这里插入图片描述

一共是输入三次123456
最后生成cert.pfx 文件
在这里插入图片描述

配置.net Core

将证书放到.netCore的程序路径中
在这里插入图片描述

修改.netCore的程序的Program.cs 文件的内容

using System.Security.Cryptography.X509Certificates;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

// 配置 Kestrel 使用 SSL 证书
app.UseHttpsRedirection();
app.Use(async (context, next) =>
{
    var certificate = new X509Certificate2(
        Path.Combine(AppContext.BaseDirectory, "myNameZhengShu", "cert.pfx"),
        "123456");
    context.Connection.ClientCertificate = certificate;
    await next();
});

app.Run();

重要的是这个,myNameZhengShu 是证书的路径,我这里是.exe程序的myNameZhengShu 的文件夹下,证书的密码是123456,证书的名称是cert.pfx

app.UseHttpsRedirection();
app.Use(async (context, next) =>
{
    var certificate = new X509Certificate2(
        Path.Combine(AppContext.BaseDirectory, "myNameZhengShu", "cert.pfx"),
        "123456");
    context.Connection.ClientCertificate = certificate;
    await next();
});

然后添加一个http的post请求,创建一个新的.cs文件并拷贝粘贴下面的内容:
访问方式是:https://localhost:7267/User?username=123
请求结果是:123, 你好,现在是:2024-06-20 22:46:01

using Microsoft.AspNetCore.Mvc;
namespace TSLServerTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {
        // POST请求的示例
        [HttpPost]
        public ActionResult<string> Post([FromQuery] string username)
        {
            // 获取当前时间
            DateTime currentTime = DateTime.Now;

            // 构建返回的字符串
            string responseMessage = $"{username}, 你好,现在是:{currentTime.ToString("yyyy-MM-dd HH:mm:ss")}";

            return Ok(responseMessage);
        }
    }
}

验证证书生效

在这里插入图片描述

在post man中发送http请求发送不了

在这里插入图片描述https就可以哦
在这里插入图片描述

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值