目录
接收multipart/form-data、application/x-www-form-urlencoded类型参数接收URL参数接收上传的文件webapi接收json参数完整控制器,启动类参考Program.cs
接收multipart/form-data、application/x-www-form-urlencoded类型参数
Post ([FromForm]TokenRequestInput user)
可以接收发送类型为multipart/form-data、application/x-www-form-urlencoded的数据
[HttpPost] public async Task<IActionResult> ChangePhoneNum([FromForm] TokenRequestInput user) { return Ok(11222); } /// <summary> /// 用户信息 /// </summary> public class TokenRequestInput { /// <summary> /// 微信 用户的openid /// </summary> public string? openid { get; set; } /// <summary> /// 微信头像图片,base64字符串 /// </summary> public string? head_img_base64 { get; set; } /// <summary> /// 微信昵称 /// </summary> public string? nichen { get; set; } }
接收URL参数
请求地址
http://localhost:5170/api/User/GetToken?code=22222
[HttpGet] public async Task<IActionResult> GetToken(string code) { var result = await wxAppletLoginBll.GetLoginToken(code); return Ok(result); }
接收上传的文件
IFormFile file这个参数是接收文件,mimeType=multipart/form-data
参数userId,通过url参数传入
/// <summary>/// 接收上传的文件/// </summary>/// <param name="file">文件二进制</param>/// <param name="userId">url参数</param>/// <returns></returns>[HttpPost]public async Task<IActionResult> GetAdd(IFormFile file, string userId){ return Ok("ok");}
webapi接收json参数
发送json参数
{ "openid": "string", "head_img_base64": "string", "nichen": "string"}
[HttpPost] public async Task<IActionResult> AddUser(TokenRequestInput user) { return Ok(3344); }
完整控制器,启动类参考
using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using WebProjectNet7.DataBaseEntity.Entity;using WebProjectNet7.IBLL;using WebProjectNet7.ViewEntity;namespace Api_BigData.Controllers{ /// <summary> /// 预警 /// </summary> [Route("api/[controller]/[action]")] [MyRequestFilter] [ApiController] public class WarningController : ControllerBase { readonly IWaringLogBll waringLogBll = AppServicesHelpter.GetServices<IWaringLogBll>(); /// <summary> /// 设置预警记录,已经读了 /// </summary> /// <param name="logId">预警id</param> /// <returns></returns> [HttpGet] public async Task<IActionResult> SetReadedAsync(long logId) { var data = await waringLogBll.SetReadedAsync(logId); return Ok(data); }}}
Program.cs
using Api_BigData;using InterfaceRegister;using Microsoft.AspNetCore.Html;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.FileProviders;using Microsoft.Extensions.Options;using Microsoft.OpenApi.Models;using Mysqlx;using Newtonsoft.Json.Serialization;using System.Reflection;using WebProjectNet7.DataBaseEntity.Tool;using WebProjectNet7.IBLL;using WebProjectNet7.IBLL_impl;using WebProjectNet7.IDAO;using WebProjectNet7.IDAO_impl;using WebProjectNet7.ViewEntity;const string title = "测试, 大数据webapi";var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllers( ops => { //全局异常过滤器,注册 ops.Filters.Add<ExceptionFilter>(); }).AddNewtonsoftJson(options =>{//不设置,字段为首字母小写; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";});// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbucklebuilder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen(options =>{ options.SwaggerDoc("v1", new OpenApiInfo { Title = title, Version = "1.0" }); // 让Swagger显示每个接口的注释 var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename)); //实体字段描述 options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "WebProjectNet7.DataBaseEntity.xml")); options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "WebProjectNet7.ViewEntity.xml"));});//依赖注入//微信业务接口builder.Services.AddSingleton<IWxAppletLoginBll, WxAppletLoginBll_impl>();//公共部分接口RegisterHandle.Register(builder);//IHttpContextAccessor 在其他程序集中获取HttpContextbuilder.Services.AddHttpContextAccessor();var app = builder.Build(); Configure the HTTP request pipeline.//if (app.Environment.IsDevelopment())//{// app.UseSwagger();// app.UseSwaggerUI();//}//生产环境也使用app.UseSwagger();app.UseSwaggerUI(options =>{ options.DocumentTitle = title;});app.Use(async (context, next) =>{ if (context.Request.Method == "OPTIONS") { //允许处理跨域 context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); context.Response.Headers.Add("Access-Control-Allow-Headers", "*"); context.Response.Headers.Add("Access-Control-Allow-Methods", "*"); await context.Response.CompleteAsync(); } else { //允许处理跨域 context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); context.Response.Headers.Add("Access-Control-Allow-Headers", "*"); context.Response.Headers.Add("Access-Control-Allow-Methods", "*"); await next(); }});string direxport = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wx_head_img");if (!System.IO.Directory.Exists(direxport)){ System.IO.Directory.CreateDirectory(direxport);}app.UseStaticFiles(new StaticFileOptions(){ RequestPath = new PathString("/wx_head_img"), FileProvider = new PhysicalFileProvider(direxport)});app.UseAuthorization();app.MapControllers();AppServicesHelpter.App = app;app.MapGet("/", () => "Hello World,欢迎," + title + ",访问/swagger 查看接口文档");app.Run();