在ASP.NET Web API中,我试图借助本文中提到的自定义值提供程序技术来读取HTTP请求头信息。
https://www.c-sharpcorner.com/article/fetch-header-information-using-customvalueprovider-in-asp-ne/
现在这项技术工作得很好,它为我提供了所需头键的值。但我想修改api控制器操作方法签名,以获取header的整个dictionary对象。
我的API控制器方法如下所示:
[HttpPost]
[Route("user-documents")]
public async Task<IHttpActionResult> GetUserDocuments([ValueProvider(typeof(CustomHeaderProviderFactory))] string Client, SearchCriteria incomingObj)
{ .... Logic ...... }
下面是CustomHeaderProviderFactory的类。
public class CustomHeaderProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(HttpActionContext actionContext)
{
return new CustomHeaderValueProvider(actionContext);
}
}
public class CustomHeaderValueProvider : IValueProvider
{
public Dictionary<string, string> objCollection;
public CustomHeaderValueProvider(HttpActionContext context)
{
objCollection = new Dictionary<string, string>();
foreach (var item in context.Request.Headers)
{
objCollection.Add(item.Key, string.Join(string.Empty, item.Value));
}
}
public bool ContainsPrefix(string prefix)
{
return objCollection.Keys.Contains(prefix);
}
public ValueProviderResult GetValue(string key)
{
if (key == null)
throw new Exception("NullReferenceException");
if (objCollection.TryGetValue(key, out string resultValue))
{
return new ValueProviderResult(resultValue, resultValue, System.Globalization.CultureInfo.InvariantCulture);
}
return null;
}
}
我想更改API方法的签名,这样我就可以访问API方法主体内的完整请求头对象。如果我能在API方法中访问完整的objCollection,那就太好了。因为我也会在方法内部使用其他头值。
请建议如何更改此代码。