• asp.net core webapi接收application/x-www-form-urlencoded和form-data参数


    • 框架:asp.net core webapi
    • asp.net core webapi接收参数,请求变量设置

    接收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);
      }
    
      /// 
      /// 用户信息
      /// 
      public class TokenRequestInput
      {
          /// 
          /// 微信 用户的openid
          /// 
          public string? openid { get; set; }
    
          /// 
          /// 微信头像图片,base64字符串
          /// 
          public string? head_img_base64 { get; set; }
    
          /// 
          /// 微信昵称
          /// 
          public string? nichen { get; set; }
    
           
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    接收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);
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    接收上传的文件

    IFormFile file这个参数是接收文件,mimeType=multipart/form-data
    参数userId,通过url参数传入

    /// 
    /// 接收上传的文件
    /// 
    /// 文件二进制
    /// url参数
    /// 
    [HttpPost]
    public async Task<IActionResult> GetAdd(IFormFile file, string userId)
    { 
        return Ok("ok");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    webapi接收json参数

    发送json参数

    {
      "openid": "string",
      "head_img_base64": "string",
      "nichen": "string"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
      [HttpPost]
      public async Task<IActionResult> AddUser(TokenRequestInput user)
      {    
          return Ok(3344);
      }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    完整控制器,启动类参考

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using WebProjectNet7.DataBaseEntity.Entity;
    using WebProjectNet7.IBLL;
    using WebProjectNet7.ViewEntity;
    
    namespace Api_BigData.Controllers
    {
        /// 
        /// 预警
        /// 
        [Route("api/[controller]/[action]")]
        [MyRequestFilter]
        [ApiController]
        public class WarningController : ControllerBase
        {
            readonly IWaringLogBll waringLogBll = AppServicesHelpter.GetServices<IWaringLogBll>();
    
    
            /// 
            /// 设置预警记录,已经读了
            /// 
            /// 预警id
            /// 
            [HttpGet]
            public async Task<IActionResult> SetReadedAsync(long logId)
            {
                var data = await waringLogBll.SetReadedAsync(logId);
                return Ok(data);
            }
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    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/swashbuckle
    builder.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 在其他程序集中获取HttpContext
    builder.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();
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
  • 相关阅读:
    第4章 决策树
    latex入门笔记
    js摄像头动态检测
    实现点击开屏效果,类似于上下方向的开关门,
    android 13/14高版本SurfaceFlinger出现VSYNC-app/VSYNC-appSf/VSYNC-sf剖析
    Linux下在编译时修改触摸板默认行为的方法
    手写小程序摇树工具(二)——遍历js文件
    竞赛 深度学习卷积神经网络垃圾分类系统 - 深度学习 神经网络 图像识别 垃圾分类 算法 小程序
    【ElasticSearch】大数据量情况下的前缀、中缀实时搜索方案
    VAPS XT开发入门教程03:程序目录说明
  • 原文地址:https://blog.csdn.net/u011511086/article/details/136375424