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的数据

csharp 复制代码
  [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

csharp 复制代码
 [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参数传入

csharp 复制代码
/// <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参数

bash 复制代码
{
  "openid": "string",
  "head_img_base64": "string",
  "nichen": "string"
}
csharp 复制代码
  [HttpPost]
  public async Task<IActionResult> AddUser(TokenRequestInput user)
  {    
      return Ok(3344);
  }

完整控制器,启动类参考

csharp 复制代码
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

csharp 复制代码
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 小时前
C#从入门到放弃
开发语言·c#
吾与谁归in1 小时前
【C#设计模式(10)——装饰器模式(Decorator Pattern)】
设计模式·c#·装饰器模式
冷眼Σ(-᷅_-᷄๑)8 小时前
Path.Combine容易被忽略的细节
c#·.net
SongYuLong的博客14 小时前
C# (定时器、线程)
开发语言·c#
百锦再15 小时前
详解基于C#开发Windows API的SendMessage方法的鼠标键盘消息发送
windows·c#·计算机外设
无敌最俊朗@16 小时前
unity3d————协程原理讲解
开发语言·学习·unity·c#·游戏引擎
程序设计实验室17 小时前
在网页上调起本机C#程序
c#
Crazy Struggle20 小时前
.NET 8 强大功能 IHostedService 与 BackgroundService 实战
c#·.net·.net core
fs哆哆20 小时前
C#编程:优化【性别和成绩名次】均衡分班
开发语言·c#
fathing21 小时前
c# 调用c++ 的dll 出现找不到函数入口点
开发语言·c++·c#