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

目录

    • 接收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);
  }

  /// 
  /// 用户信息
  /// 
  public class TokenRequestInput
  {
      /// 
      /// 微信 用户的openid
      /// 
      public string? openid { get; set; }

      /// 
      /// 微信头像图片,base64字符串
      /// 
      public string? head_img_base64 { get; set; }

      /// 
      /// 微信昵称
      /// 
      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参数传入

/// 
/// 接收上传的文件
/// 
/// 文件二进制
/// url参数
/// 
[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
{
    /// 
    /// 预警
    /// 
    [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);
        }
	}
}

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();
本站无任何商业行为
个人在线分享 » asp.net core webapi接收application/x-www-form-urlencoded和form-data参数
E-->