[英]Assign Value In Base Controller From Post Request In ASP.Net core web API
I have many controllers which are dependent on one variable which is let's say projectId. 我有很多控制器都依赖于一个变量,即projectId。
So on every request of all methods I have to parse projectId as below. 因此,在所有方法的每个请求上,我都必须解析如下的projectId。 so is it possible to get this value in base controller variable and use it directly for all methods. 因此可以在基本控制器变量中获取此值,并将其直接用于所有方法。 I found some actionexecuting and initialize way, but they were examples in .net, I could not manage to get in asp.net core web API. 我找到了一些动作执行和初始化方式,但是它们只是.net中的示例,我无法设法获得asp.net核心Web API。
public void Save([FromBody]JObject data)
{
new SaveMethod((int)data["projectId"])
.Save((string)data["otherData"]);
}
You can simply use the default model binding , create a class and application will automatically bind to object after getting the post request : 您可以简单地使用默认的模型绑定,创建一个类,应用程序将在收到发布请求后自动绑定到对象:
[HttpPost]
public void Post([FromBody] MyValue value)
{
}
public class MyValue {
public int projectID { get; set; }
//Other property
}
And the request will be something like : 请求将是这样的:
POST https://localhost:XXXX/api/values
Content-Type: application/json
{"projectID": 1}
Then you can save to session for later access if you want the data available across requests. 然后,如果希望跨请求的数据可用,则可以保存到会话以供以后访问。
Or you can just not use model binding(remove [FromBody]
parameter , model binding execute before filter) , and get the request body in OnActionExecuting
and save to session for later access : 或者,您不能只使用模型绑定(删除[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;
}
}
And you can make your controller inherits MyControllerBase
and modify that to meet your requirement . 您可以使您的控制器继承MyControllerBase
并对其进行修改以满足您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.