我使用Audit.Net对我的ASP.NET Razor应用程序进行审计,结果以JSON格式存储在SQL Server数据库中。表的名称为AuditTrail,JSON结果存储在名为JsonData的列中。下面是典型的JSON输出:
我该如何从JSON输出中选择特定的参数,例如“Action.UserName”,而无需输出整个JSON输出,目前的情况是我需要将整个JSON输出传递给视图。目前我的做法是将JSON输出表示为一个类并连接到数据库,但它不起作用。
{
"EventType": "GET /Account/Menu",
"Environment": {
"UserName": "xxx",
"MachineName": "xxx-MacBook-Pro",
"DomainName": "xxx-MacBook-Pro",
"CallingMethodName": "xxx.Areas.Identity.Pages.Account.MenuModel.OnGet()",
"AssemblyName": "xxx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"Culture": ""
},
"StartDate": "2020-12-10T14:44:47.067556Z",
"EndDate": "2020-12-10T14:44:47.067788Z",
"Duration": 0,
"Action": {
"TraceId": "xxxx",
"HttpMethod": "GET",
"ControllerName": "Identity",
"ActionName": "/Account/Menu",
"ViewPath": "/Account/Menu",
"ActionParameters": {},
"RequestBody": {},
"ResponseBody": {
"Type": "PageResult"
},
"UserName": "xxx@gmail.com",
"RequestUrl": "https://localhost:5001/Identity/Account/Menu",
"IpAddress": "::1",
"ResponseStatusCode": 200
}
}
我该如何从JSON输出中选择特定的参数,例如“Action.UserName”,而无需输出整个JSON输出,目前的情况是我需要将整个JSON输出传递给视图。目前我的做法是将JSON输出表示为一个类并连接到数据库,但它不起作用。
public class Action
{
public string TraceId { get; set; }
public string HttpMethod { get; set; }
public string ControllerName { get; set; }
public string ActionName { get; set; }
public string ViewPath { get; set; }
public string UserName { get; set; }
public string RequestUrl { get; set; }
public string IpAddress { get; set; }
public int ResponseStatusCode { get; set; }
}
public class Audits
{
public List<Action> Actions { get; set; }
}
string connectionString = "Data Source=localhost;User ID=sa;Password=xxx;initial
catalog=xxx.db;integrated security=false;";
public string UserName { get; set; }
public string IpAddress { get; set; }
public string HttpMethod { get; set; }
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = "SELECT JsonData FROM AuditTrail";
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
List<AuditLog> auditLogs1 = new List<AuditLog>();
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
AuditLog audit1 = new AuditLog();
audit1.User = reader["JsonData"].ToString();
auditLogs1.Add(audit1);
}
connection.Close();
}
var JsonResult = JsonConvert.SerializeObject(auditLogs1);
var JsonResult1 = JsonConvert.DeserializeObject<Audits>(JsonResult);
foreach (var x in JsonResult1.Actions)
{
UserName = x.UserName;
HttpMethod = x.HttpMethod;
IpAddress = x.IpAddress;
}
}