在DelegatingHandler中设置自定义标头的正确方法是什么

时间:2019-01-09 06:57:07

标签: c# asp.net asp.net-web-api asp.net-web-api2

我要记录相关性ID和所有日志消息。 我使用DelegatingHandler向请求和响应标头添加相关ID,我遇到了两种方法:

第一

// In the DelagatingHandler
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    ...
    request.Headers.Add("X-Correlation-Id", correlationId);
    ...
}

为了在记录器类中获取此标头,我必须执行以下(HttpContext.Current.Request.Headers不包含此标头)

var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
var corId = requestMessage.Headers.GetValues("X-Correlation-Id");

第二:

// In the DelegatingHandler
HttpContext.Current.Request.Headers.Add("X-Correlation-Id", correlationId);

// In the logger class
var correlationId = HttpContext.Current.Request.Headers.Get("X-Correlation-Id");

哪种方法是正确的? 为什么HttpContext.Current.Request在第一种方法中不包含此标头?

1 个答案:

答案 0 :(得分:0)

我要说的第一种方法是private List<SingListBean> getAllSing(Context context) { int flag = 1; List<SingListBean> listBeans = new ArrayList<>(); Cursor cursor = context.getContentResolver().query (MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); while (cursor.moveToNext()) { String singName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); String singAlbum = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)); Long _size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)); int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)); String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)); listBeans.add(new SingListBean(flag++, singName, singAlbum, _size, duration, url)); } return listBeans; } 。单元测试很容易。坦白地说,所有请求前数据都与HttpRequestMessage一起提供。

要回答您的第二个问题,有一个很好的回答here