在blazor
中接收并处理Post
请求,其实和WebAPI
差不多,操作如下:
新建一个文件,这里以
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; }
}
在Program.cs中注册
// other code...
// Add controllers
builder.Services.AddControllers();
// other code...
// Map controllers
app.MapControllers();
正常运行使用即可