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就可以哦