使用JSON.NET序列化字典时,似乎NullValueHandling忽略了该设置。
var dict = new Dictionary<string, string>
{
["A"] = "Some text",
["B"] = null
};
var json = JsonConvert.SerializeObject(dict, Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Console.WriteLine(json);
Run Code Online (Sandbox Code Playgroud)
输出:
{
"A": "Some text",
"B": null
}
Run Code Online (Sandbox Code Playgroud)
我希望json输出中仅包含键为“ A”的KVP,而省略了KVP“ B”。
如何告诉Json.NET仅序列化不包含空值的条目?
用户可以通过向 ASP.NET Core 控制器发送请求来触发长时间运行的作业。当前,控制器执行作业,然后发送 200 OK 响应。问题是客户端必须等待相当长的时间才能得到响应。
这就是我目前尝试在后台任务中处理作业的原因。我正在使用一个IBackgroundTaskQueue存储所有作业的地方,并且IHostedService在有新作业入队时处理作业。它类似于Microsoft 文档中的代码。
但该作业确实需要访问数据库,因此用户必须使用 Active Directory 进行身份验证。因此,我需要访问HttpContext.User后台任务中的属性。不幸的是,在HttpContext发送响应时和作业处理开始之前,它会被处理掉。
public class Job
{
public Job(string message)
{
Message = message;
}
public string Message { get; }
}
Run Code Online (Sandbox Code Playgroud)
控制器将新作业排入任务队列。
[HttpGet]
public IActionResult EnqueueJob()
{
var job = new Job("Hello World");
this.taskQueue.QueueBackgroundWorkItem(job);
return Accepted();
}
Run Code Online (Sandbox Code Playgroud)
public class BackgroundTaskQueue : IBackgroundTaskQueue
{
private ConcurrentQueue<Job> jobs = new ConcurrentQueue<Job>();
private SemaphoreSlim signal = new SemaphoreSlim(0);
public void QueueBackgroundWorkItem(Job …Run Code Online (Sandbox Code Playgroud) 在解析我自己的简单查询语言时,我正在为 NEST 客户端生成 Elasticsearch 查询。也就是说,解析器返回一个QueryDescriptor(它是 的别名Func<QueryContainerDescriptor<SearchResult>, QueryContainer>),然后可以使用它从 Elasticsearch 获取搜索结果。
当输入是类似 的查询时,将调用以下nestedObject.someField:someValue方法。GetQueryDescriptorquery == "nestedObject.someField:someValue"
// NestedObjectQueryToken.cs
public Func<QueryContainerDescriptor<SearchResult>, QueryContainer> GetQueryDescriptor(string query)
{
// GetFieldNames() extracts the fields that the user search in from the query
// (there could possibly be more than one field present)
var nestedFields = query.GetFieldNames().Select(fieldName => new Field("nestedObject." + fieldName));
return descriptor => descriptor.NestedFieldSearch(query, _ => _.Fields(fields));
}
Run Code Online (Sandbox Code Playgroud)
// QueryDescriptorExtensions.cs
public static QueryContainer NestedFieldSearch(this QueryContainerDescriptor<SearchResult> descriptor,
string query, FieldsDescriptor …Run Code Online (Sandbox Code Playgroud)