ASP.NET 如果找到自定义标头,则消息处理程序返回 json
本文关键字:消息处理 程序 json 返回 如果 NET 自定义 ASP | 更新日期: 2023-09-27 18:36:43
以下情况是否可能:
创建一个消息处理程序,用于检查每个传入的请求。如果请求包含自定义标头键:"My-Header",并且其值为:"True",则停止请求并向客户端返回自定义 json,否则,如果标头不存在或标头存在但值为"False",则允许请求通过。
听起来你会按照下面显示的代码行进行操作。这是假设您要发回的 JSON 在此处由 ErrorModel
表示。若要将处理程序添加到 ASP.NET Web API 处理程序管道,请查看这篇关于它如何连接的好文章。
public class MyHeaderHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
string headerTokenValue;
const string customHeaderKey = "My-Header";
if (!request.Headers.TryGetValues(
customHeaderKey,
out headerTokenValue)
|| headerTokenValue.ToLower() != "true")
{
return base.SendAsync(request, cancellationToken);
}
return Task<HttpResponseMessage>.Factory.StartNew(
() =>
{
var response = new HttpResponseMessage(
HttpStatusCode.Unauthorized);
var json = JsonConvert.SerializeObject(
new ErrorModel
{
Description = "error stuff",
Status = "Ooops"
});
response.Content = new StringContent(json);
// Ensure return type is JSON:
response.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
return response;
});
}
}
我猜也许这样更好?
............
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Forbidden);
var json = JsonConvert.SerializeObject(
new ErrorModel
{
Description = "error stuff",
Status = "Ooops"
});
response.Content = new StringContent(json);
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;