1.创建 APS.NET CORE6.0 WEB API项目
默认选项即可
源代码:
项目文件展开:
launchSettings.json
{"$schema": "https://json.schemastore.org/launchsettings.json","iisSettings": {"windowsAuthentication": false,"anonymousAuthentication": true,"iisExpress": {"applicationUrl": "http://localhost:19488","sslPort": 44308}},"profiles": {"ServerSideApi": {"commandName": "Project","dotnetRunMessages": true,"launchBrowser": true,//"launchUrl": "swagger",//"applicationUrl": "https://192.168.3.24:8080;http://192.168.3.24:8081","environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development"}},"IIS Express": {"commandName": "IISExpress","launchBrowser": true,"launchUrl": "swagger","environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development"}}}
}
Controllers\HomeController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ServerSide.BLL;
using ServerSide.Common;
using ServerSide.Models;namespace ServerSideApi
{[Route("api")][ApiController]public class HomeController : ControllerBase{readonly IService<Users>? usersService;public HomeController(IService<Users> usersService){this.usersService = usersService;}[HttpGet("GetLogin")]//GetLogin {}{account}/{password}public async Task<string> Get(string account, string password){//jwt token//登录成功之后生成令牌{account:'zhangsan',password:'123456'}string? token = "0";//token令牌Users? users= await usersService!.GetAsync(m => m.Account == account&& m.Password == DataEncrypt.MD5Encrypt(password));if (users != null) {token = Guid.NewGuid().ToString(); //users.Account;RedisCache.SetCache(token, users.Account!);//36不会重复}return token;}}
}
Controllers\SystemActionController.cs
using Bogus.Bson;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ServerSide.Common;
using ServerSide.DAL;
using ServerSide.Models;
using System.Text.Json.Nodes;namespace ServerSideApi.Controllers
{public class SystemActionController : Controller{private string msgModel = "{{\"code\":{0},\"message\":\"{1}\",\"result\":{2}}}";//检查用户名是否已注册/// <summary>/// 获取对应订单激活码/// </summary>/// <param name="OrderInfo">订单号</param>/// <returns></returns>#region 获取激活码[HttpGet("GetActionKey")]//GetLogin {}{account}/{password}public string GetActionKey(string OrderInfo){string systemActionKey = string.Empty;int i = 0;using (EFContext db=new EFContext()){systemActionKey = db!.SystemActionEntity!.ToList()!.Where((s) => s.OrderInfo == OrderInfo && s.ActionStatId == 2).FirstOrDefault()!.KeyCode!;if(systemActionKey.Length>5){db!.SystemActionEntity!.ToList()!.ForEach((s) => {if (s.KeyCode == systemActionKey){s.ActionStatId = 3;}i=db!.SaveChanges();LogHelper.Info(i > 0 ? $@"OrderInfo:{OrderInfo} Action Key Read {systemActionKey} PASS" : $@"OrderInfo:{OrderInfo} Action Key Read FAIL"); });}if (i>0||systemActionKey.Length>5)return string.Format(msgModel, (int)(ResponseCode.成功), "成功", systemActionKey);elsereturn string.Format(msgModel, (int)(ResponseCode.操作失败), "失败", "null");}}#endregion/// <summary>/// 获取对应订单末激活信息/// </summary>/// <param name="OrderInfo">订单信息</param>/// <returns></returns>#region 获取末激活数据[HttpGet("GetAllNotActionData")]//GetLogin {}{account}/{password}public string GetAllNotActionData(string OrderInfo){List<SystemActionEntity>systemActionEntities = new List<SystemActionEntity>();using(EFContext db=new EFContext()){db!.SystemActionEntity!.ToList()!.ForEach((s) => { if(s.OrderInfo==OrderInfo&&s.ActionStatId==2)//1.已激活、2.末激活中、3.激活中{systemActionEntities.Add(s);}});}LogHelper.Info(systemActionEntities.Count > 0 ? $@"OrderInfo:{OrderInfo} Not Action Data Read PASS" : $@"OrderInfo:{OrderInfo} Not Action Data Read FAIL");if (systemActionEntities.Count>0){return string.Format(msgModel, (int)(ResponseCode.成功), "成功", JsonConvert.SerializeObject(systemActionEntities));}elsereturn string.Format(msgModel, (int)(ResponseCode.操作失败), "失败", JsonConvert.SerializeObject(systemActionEntities));}#endregion/// <summary>/// 获取所有激活数据/// </summary>/// <param name="OrderInfo">订单信息</param>/// <returns></returns>#region 获取所有已激活的数据[HttpGet("GetAllIsActionData")]public string GetAllIsActionData(string OrderInfo) //List<SystemActionEntity>{lock(this){List<SystemActionEntity> systemActionEntities = new List<SystemActionEntity>();using (EFContext db = new EFContext()){db!.SystemActionEntity!.ToList()!.ForEach((s) => {if (s.OrderInfo == OrderInfo && s.ActionStatId == 1)//1.已激活、2.末激活中、3.激活中{systemActionEntities.Add(s);}});}if (systemActionEntities.Count > 0){return string.Format(msgModel, (int)(ResponseCode.成功), "成功", JsonConvert.SerializeObject(systemActionEntities));}else{return string.Format(msgModel, (int)(ResponseCode.操作失败), "失败", JsonConvert.SerializeObject(systemActionEntities));}} }#endregion/// <summary>/// 更新激活数据/// </summary>/// <param name="macAddress">mac地址</param>/// <param name="BarcodeNo">sn条码</param>/// <param name="keyCode">激活码</param>/// <returns></returns>#region 更新激活数据[HttpPut("UpdateActionData")]public string UpdateActiopnData(string macAddress,string BarcodeNo,string keyCode){using(EFContext db = new EFContext()) {db!.SystemActionEntity!.ToList()!.ForEach((s) => {if(s.KeyCode==keyCode){s.MacAddress = macAddress;s.ActionStatId = 1;s.BarcodeNo = BarcodeNo;}});int result=db!.SaveChanges();if(result>0){return string.Format(msgModel, (int)(ResponseCode.成功), "成功", $@"KeyCode:{keyCode} Data Update Pass!!");}else{return string.Format(msgModel, (int)(ResponseCode.操作失败), "失败", $@"KeyCode:{keyCode} Data Update Fail!!");}}}#endregion}
}
Controllers/UsersController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ServerSide.BLL;
using ServerSide.Common;
using ServerSide.Models;
using ServerSideApi.Filters;namespace ServerSideApi
{[ApiController, Route("api/users"),TypeFilter(typeof(UsersAuthorizeAttribute))]public class UsersController : ControllerBase{readonly IService<Users>? usersService;public UsersController(IService<Users> usersService){this.usersService = usersService;}//https://localhost:8080/api/users/zhangsan//HttpGet查询 HttpPost添加 HttpPut修改 HttpDelete删除//[HttpGet]//public List<Users> Get()//{// return usersService!.GetAll().ToList();//}//[HttpGet("{account}")]//public Users Get(string account)//{// return usersService!.Get(account);//}//[HttpGet("{account}/{password}")]//GetLogin//public Users Get(string account, string password)//{// return usersService!.GetAll(m => m.Account == account// && m.Password == DataEncrypt.MD5Encrypt(password))// .FirstOrDefault()!;//}//[HttpPost]//添加 FromBody:规范化标识,告诉服务器是以http请求正文形式发送模式(非URL)//public int Post([FromBody] Users users)//对象形参//{// users.Password = DataEncrypt.MD5Encrypt(users.Password!);// return usersService!.Add(users);//}//[HttpPut]//修改//public int Put([FromBody] Users users)//对象形参//{// return usersService!.Update(users);//}//[HttpDelete]//删除//public int Put(string account)//对象形参//{// return usersService!.Remove(account);//}//特性[]//[TypeFilter(typeof(UsersAuthorizeAttribute))]//第一种方式//第二种方式[HttpGet]public async Task<IEnumerable<Users>> Get()//xml json List<Users>{return await usersService!.GetAllAsync();//结果集List}[HttpGet("{account}")]public async Task<Users> Get(string account){return await usersService!.GetAsync(account);}[HttpPost]//添加 FromBody:规范化标识,告诉服务器是以http请求正文形式发送模式(非URL)public async Task<int> Post([FromBody] Users users)//对象形参{users.Password = DataEncrypt.MD5Encrypt(users.Password!);return await usersService!.AddAsync(users);}[HttpPut]//修改public async Task<int> Put([FromBody] Users users)//对象形参{users.Password = DataEncrypt.MD5Encrypt(users.Password!);try{return await usersService!.UpdateAsync(users);}catch (Exception){return 0;}}[HttpDelete("delete/{account}")]//删除public async Task<int> Delete(string account)//对象形参{return await usersService!.RemoveAsync(account);}}
}
Filters/UsersAuthorizeAttribute.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ServerSide.Common;namespace ServerSideApi.Filters
{public class UsersAuthorizeAttribute : IAuthorizationFilter{public void OnAuthorization(AuthorizationFilterContext context){string? token = context.HttpContext.Request.Headers["token"];//"" null//有没有带Tokenif (string.IsNullOrEmpty(token)){//进来后直接返回到前端context.Result = new JsonResult(0);//文本类型text 没有授权}else//判断token是否正确{string? key = RedisCache.GetCache(token);//36位字符串在redisif (string.IsNullOrEmpty(token)){context.Result = new JsonResult(0);//没有授权}}//没进去,正常进入控制器>动作方法}}
}
Program.cs
using Microsoft.EntityFrameworkCore;
using ServerSide.BLL;
using ServerSide.DAL;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();//注入业务类
builder.Services.AddScoped(typeof(IRepository<>),typeof(Repository<>));//IOC容器
builder.Services.AddScoped(typeof(IService<>),typeof(Service<>));//注入EFCore对象
string connStr = builder.Configuration.GetConnectionString("connStr")!;builder.Services.AddDbContext<EFContext>(options=>options.UseSqlServer(connStr));//webapi请求方案
builder.Services.AddCors(options =>
{options.AddPolicy("AllowAll",options=>options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()//method:put delete post get restful风格架构);
});//enctype="multpart/form-data" 请求头 token="asdjasdasg123123"
//http://www.baidu.com/product?id=1001 url传参
//<form ><input type="text" name="username" /></form> 表单传参var app = builder.Build();// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
// app.UseSwagger();//Swagger工具
// app.UseSwaggerUI();
//}
app.UseSwagger();
app.UseSwaggerUI(c =>
{c.RoutePrefix = "";c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test Web Api");
}
);
app.UseCors("AllowAll");//使用跨域方案
app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
设置 Swagger UI 为起始页
打开 launchSettings.json
文件
屏蔽以下两行代码
打开 Program.cs
文件
屏蔽原来的环境判断,新增以下代码
app.UseSwagger();
app.UseSwaggerUI(c =>{c.RoutePrefix = "";c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1"); //第二个参数可自定义命名});
发布项目
发布项目:右击项目 → 发布
选择文件夹
选择文件夹位置,这个位置就是 项目发布后的文件 所在的位置
检查 目标位置 的文件夹是否存在,不然会报错
点击 更多操作→编辑 可根据自己的项目进行设置
设置好后,点击 发布
当输出显示成功即发布成功;若失败会显示具体信息供排查
2、在 IIS 部署
这里就不再阐述了,引用这位博主的文章
如何安装IIS
安装 Hosting Bundle
点击 下载 .NET(Linux、macOS 和 Windows)
下载安装 Hosting Bundle
我这里安装的是 Hosting Bundle 6.0,可根据情况适当更改
安装成功后,打开 IIS →模块 后会在列表看到 AspNetCoreModuleV2
右键 应用程序池 添加应用程序池
选择 无托管代码
右键 网站 添加网站
点击浏览,则会跳转到 Swagger UI 界面
3.内网穿透
打开 控制面板 → 防火墙
端口 → 特定本地端口
然后一直按 下一步,最后填写 名称 即可完成
展示效果: