捕获和缓存每个请求的标头

时间:2017-07-26 01:12:22

标签: c# asp.net .net asp.net-web-api visual-studio-2017

我们通过强制客户端通过我们的应用程序进行CRUD调用来限制对企业系统的访问,然后我们的应用程序会将相同的请求转发到其目的地,从而保存标题信息。

  1. 客户向ApiController
  2. 发出请求
  3. 我们将请求传递给服务层
  4. 服务层将请求转发到其预期的企业系统目标。
  5. 详细说明以上几点:

    客户端针对此发出请求:

        [HttpGet]
        [Route("opportunities({id:guid})")]
        [Route("opportunities")]
        public async Task<HttpResponseMessage> GetOpportunity()
        {
            var query = Request.RequestUri.AbsolutePath.Split('/').Last() + Request.RequestUri.Query;
            var response = await _opportunityService.GetOpportunity(query);
            return response;
        }
    

    服务方法GetOpportunity定义为:

        public async Task<HttpResponseMessage> GetOpportunity(string query)
        {//at the line below is where i want to send the same headers that were passed in originally at step 1
            var response = Client.Instance.GetAsync(Client.Instance.BaseAddress + query); //this is just using HttpClient to make this call
            var responseType = response.Result.StatusCode;
            if (responseType == HttpStatusCode.NotFound)
                return new HttpResponseMessage
                {
                    StatusCode = responseType
                };
            return await response;
        }
    

    我们如何保存第1步中的标题信息?

    通过使用以下中间件,我已经能够获取所有头信息;但是,我不确定如何缓存或将它们提供给服务层:

    public class HeaderAuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var headers = actionContext.Request.Headers;
        }
    
    }
    

1 个答案:

答案 0 :(得分:1)

您基本上充当代理人。我看到了一些可能的选择。

一种方法是将原始请求作为显式依赖项传递给服务

[HttpGet]
[Route("opportunities({id:guid})")]
[Route("opportunities")]
public async Task<HttpResponseMessage> GetOpportunity() {
    var response = await _opportunityService.GetOpportunity(this.Request);
    return response;
}

并在那里提取信息

public async Task<HttpResponseMessage> GetOpportunity(HttpRequestMessage Request) {
    //at the line below is where i want to send the same headers that were passed in originally at step 1
    var query = Request.RequestUri.AbsolutePath.Split('/').Last() + Request.RequestUri.Query;
    var headers = Request.Headers;
    var url = Client.Instance.BaseAddress + query;
    //create new request and copy headers
    var proxy = new HttpRequestMessage(HttpMethod.Get, url);
    foreach (var header in headers) {
        proxy.Headers.Add(header.Key, header.Value);
    }
    var response = await Client.Instance.SendAsync(proxy);//This is an assumption.
    var responseType = response.StatusCode; //Do not mix blocking calls. It can deadlock
    if (responseType == HttpStatusCode.NotFound)
        return new HttpResponseMessage {
            StatusCode = responseType
        };
    return response;
}

如果您不想混合图层和问题,可以将所需信息提取到您自己的模型中,然后将其传递给服务,以便重新创建所需的请求。