您可以简单地使用默认模型绑定,创建一个类,应用程序在收到 post 请求后会自动绑定到对象:
[HttpPost]
public void Post([FromBody] MyValue value)
{
}
public class MyValue {
public int projectID { get; set; }
//Other property
}
请求将类似于:
POST https://localhost:XXXX/api/values
Content-Type: application/json
{"projectID": 1}
如果您希望跨请求的数据可用,您可以save to session 供以后访问。
或者你可以不使用模型绑定(删除[FromBody]参数,模型绑定在过滤器之前执行),并在OnActionExecuting中获取请求正文并保存到会话以供以后访问:
public class MyControllerBase: Controller
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
var bodyStr = "";
var req = context.HttpContext.Request;
// Allows using several time the stream in ASP.Net Core
req.EnableRewind();
// Arguments: Stream, Encoding, detect encoding, buffer size
// AND, the most important: keep stream opened
using (StreamReader reader
= new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
{
bodyStr = reader.ReadToEnd();
}
// Rewind, so the core is not lost when it looks the body for the request
req.Body.Position = 0;
}
}
您可以让您的控制器继承 MyControllerBase 并对其进行修改以满足您的要求。