Blazor 处理 Post 请求

在blazor中接收并处理Post请求,其实和WebAPI差不多,操作如下: 新建一个文件,这里以Callback.cs举例,引用Microsoft.AspNetCore.Mvc: using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; usin

blazor中接收并处理Post请求,其实和WebAPI差不多,操作如下:

  1. 新建一个文件,这里以Callback.cs举例,引用Microsoft.AspNetCore.Mvc

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text;

namespace WeChatHelper.Model;

[ApiController]
[Route("api/[controller]")]
public class CallbackController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> PostData([FromBody] WxApi data)
    {
        // 获取请求体
        using var reader = new StreamReader(Request.Body, Encoding.UTF8);
        var body = await reader.ReadToEndAsync();

        Console.WriteLine($"Receive:\n{body}");

        // 返回请求体和请求头信息
        return Ok(new
        {
            message = "Data received successfully",
        });
    }
}

public class WxApi
{
    public int ServerPort { get; set; }
    public string? selfwxid { get; set; }
    public int sendorrecv { get; set; }
    public int msgnumber { get; set; }
    public string? msglist { get; set; }
}
  1. 在Program.cs中注册

// other code...

// Add controllers
builder.Services.AddControllers();

// other code...

// Map controllers
app.MapControllers();
  1. 正常运行使用即可

LICENSED UNDER CC BY-NC-SA 4.0
Comment