如何捕捉和保存发布到宁静的asp.net网页API JSON数据 [英] How to catch and save json data posted to restful asp.net web api
问题描述
我有这样的code:
[Route]
public HttpResponseMessage PostData[FromBody] DataModel data)
{
... implementation...
}
这自动绑定/ JSON数据转换成我的数据模型。不过,我想保存/赶上被张贴在原始JSON文件并将其保存为日志记录。
我如何能做到这一点有什么建议?
This automatically binds / converts the json data to my data model. However, I would like to save / catch the raw json file that was posted and save it for logging purposes. Any suggestions on how I can achieve this?
推荐答案
您可以做下面的,然后使用JSON转换器将字符串转换成JSON更高版本。
You can just do the below and then use JSON converter to convert the string to JSON later.
[HttpPost]
public HttpResponseMessage PostData([FromBody] string text)
{
// log text.
DataModel data = JsonConvert.DeSerialize<DataModel>(text);
}
或者你也可以做到,
Or you can also do,
[HttpPost]
public HttpResponseMessage PostData()
{
string text = Request.Content.ReadAsStringAsync().Result;
//log text
DataModel data = JsonConvert.DeSerialize<DataModel>(text);
}
既然你提到它是记录,你可能要考虑在Web API过滤器或委托处理这样做 - 在每一个操作方法,使逻辑更集中,而不是具有逻辑
Since you mention it is for logging, you might want to consider doing this in a Web API filter or a delegating handler - to make the logic more centralized instead of having the logic in each action method.
public class LogApiRequest : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var text = actionContext.Request.Content.ReadAsStringAsync().Result;
MyLogger.Log(LogLevel.INFO, text);
base.OnActionExecuting(actionContext);
}
}
,然后注册您的过滤器 - 通常WebApiConfig.cs或装饰你的操作方法或控制器类与过滤
and then register your filter - typically in WebApiConfig.cs or decorate your action method or controller class with the filter.
config.Filters.Add(new LogApiRequest());
这篇关于如何捕捉和保存发布到宁静的asp.net网页API JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!