C#HttpClient刷新令牌策略

时间:2018-04-21 07:48:37

标签: c# httpclient delegatinghandler

由于Microsoft recommends HttpClient创建一次并在程序的整个生命周期中重复使用,我想知道如何更新DefaultRequestHeaders,例如,令牌已过期且需要刷新。

DefaultRequestHeaders更不是线程安全的(据我所知)和那里定义的头文件列表,由所有可能挂起的请求共享。 Clear()列表和Add()带有新令牌的标头,似乎不是明智之举。

更新

更准确地说,我不希望/需要为每个请求更改请求标头。只有当我获得HTTP 401状态代码时。

1 个答案:

答案 0 :(得分:3)

在DI容器注册表阶段注册IHttpClient时,使用HttpClient连接消息处理程序,或使用其他模式(如工厂或单例)返回带有自定义消息处理程序的IHttpClient实例。检查出站呼叫并添加必要的标头。

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/httpclient-message-handlers

示例标题邮件处理程序

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <header>
    <div class="col-md-3 col-lg-3 col-xs-3">
      <div>
        <form class="navbar-form">
          <div class="input-group">
            <input type="text" id="searchQuestion" class="form-control" placeholder="Search" name="q">
            <div class="input-group-btn">
              <button type="button" class="btn btn-default" style="height: 3px!important;" id="searchSubmit"><i class="glyphicon glyphicon-search"></i></button>
            </div>
          </div>
        </form>
      </div>
    </div>

  </header>
  <div id="main" class="main">
    <p>this shoul be fade out</p>
  </div>
  <div id="searchPage" style="display: none;">
    <section class="col-xs-12 col-sm-6 col-md-12">
      <article id="smartFarming" class="search-result row" style="display: none;">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/smartFarming.html" title="smart farming solutions" class="thumbnail"><img src="images/banner-11-1900x570.jpg" alt="smart farming solutions" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/smartFarming.html" title="smart farming solutions">smart farming solutions</a></h3>
          <p>For farmers and growers, the Internet of Things has opened up extremely productive ways to cultivate soil and raise livestock with the use of affordable, easy-to-install sensors and an abundance of insightful data they offer.</p>
          <span class="plus"><a href="./html/smartFarming.html" title="smart farming solutions"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="smartEnergyMonitoring" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/smartEnergyMonitoring.html" title="smartEnergyMonitoring" class="thumbnail"><img src="images/Dashboard1.png" alt="smart farming solutions" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/smartEnergyMonitoring.html" title="smartEnergyMonitoring">smart Energy Monitoring</a></h3>
          <p>Real energy management requires an energy monitoring system, which means knowing how much energy you are using. If you know how much energy your home is using and when it’s using it, you can better respond to that usage and take control of your
            costs.</p>
          <span class="plus"><a href="./html/smartEnergyMonitoring.html" title="smartEnergyMonitoring"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="smartIoTBasedDigitalSignage" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/smartIoTbasedDigitalSignage.html" title="smartIoTbasedDigitalSignage" class="thumbnail"><img src="images/nahlad_final_01_603b659a0c0b9e3c3a92549c0aefc11a.jpg" alt="smartIoTbasedDigitalSignage" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/smartIoTbasedDigitalSignage.html" title="smart IoT based Digital Signage">smart IoT based Digital Signage</a></h3>
          <p>Smart Digital Signage Solutions is a result of SKYMICS research and development to provide an affordable but complete and versatile solution for private sectors and SMEs.</p>
          <span class="plus"><a href="./html/smartIoTbasedDigitalSignage.html" title="smart IoT based Digital Signage"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="smartSurvey" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/smartSurveySolutions.html" title="smartSurveySolutions" class="thumbnail"><img src="images/mmc-web.jpg" alt="smartSurveySolutions" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/smartSurveySolutions.html" title="smartSurveySolutions">smart Survey Solutions</a></h3>
          <p>
            Smart Survey Solutions allows users to quickly create intuitive, powerful, onlined question-and-answer (but there is no need for internet) surveys that can work for tens to thousands of participants without much effort.
          </p>
          <span class="plus"><a href="./html/smartSurveySolutions.html" title="smartSurveySolutions"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="smartHydroponics" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/smartHydroponics.html" title="smartHydroponics" class="thumbnail"><img src="images/Biopod_Inhabitat.jpg" alt="smartHydroponics" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/smartHydroponics.html" title="smartHydroponics">smart Hydroponics</a></h3>
          <p>At Skymics we have come up with the solution that can help gardeners and farmers get the most out of their efforts by using sensors that monitor the necessary factors needed for growing a plant. We designed a self-contained, automatic, connected
            hydroponic growing environment by IOT. All it needs are some seeds, water and nutrient solution</p>
          <span class="plus"><a href="./html/smartHydroponics.html" title="smartHydroponics" ><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="smartEnvironmentalMonitoring" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/smartEnvironmentalMonitoring.html" title="smartEnvironmentalMonitoring" class="thumbnail"><img src="images/DYv6dbPVMAAudpy.jpg" alt="smartEnvironmentalMonitoring" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/smartEnvironmentalMonitoring.html" title="smartEnvironmentalMonitoring">smart Environmental Monitoring</a></h3>
          <p>This solution helps us to collect the environmental data in different parts of the city. The data will be stored on the cloud and analysed for further use which includes forecast of the weather status, measurement of the air pollution and so
            on. Results will be used for commercial use and public benefit.
          </p>
          <span class="plus"><a href="./html/smartEnvironmentalMonitoring.html" title="smartEnvironmentalMonitoring"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="smartBuildingManagement" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/smartBuildingManagement.html" title="smartBuildingManagement" class="thumbnail"><img src="images/Smart-building-automation.jpg" alt="smartBuildingManagement" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/smartBuildingManagement.html" title="smartBuildingManagement">smart Building Management</a></h3>
          <p>Skymics Smart Building Management System is a new way to manage your building easier in order to increase operational and energy efficiency. Our solutions can successfully integrate, install and maintain building management systems and provide
            life cycle support for any type and scale of building. We are making it easier to increase the operational performance of the facility as well as the comfort and safety of building occupants</p>
          <span class="plus"><a href="./html/smartBuildingManagement.html" title="smartBuildingManagement"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="skyMicsInvention" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/invention.html" title="invention" class="thumbnail"><img src="images/innovation-solutions-title2.jpg" alt="invention" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/invention.html" title="invention">invention</a></h3>
          <p>65% of the world’s population has no Internet access and therefore have no opportunity to gain information and knowledge. SKYMICS E-Learning hardware solutions offers the new technology that can bring the online and electronic education to anywhere
            in the world</p>
          <span class="plus"><a href="./html/invention.html" title="invention"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="mobileAppRobotechClub" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/mobileApp.html" title="mobileApp" class="thumbnail"><img src="images/1494404290-ca13-jpg.jpg" alt="mobileApp" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/mobileApp.html" title="mobile App">mobile App</a></h3>
          <p>Today, we have a computer in our pocket that is more than 100,000 times faster than the first home computers. It is connected to every other computer on the planet and can access virtually every piece of human knowledge ever created, nearly
            instantaneously</p>
          <span class="plus"><a href="./html/mobileApp.html" title="mobile App"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
      <article id="mobileLearning" style="display: none" class="search-result row">
        <div class="col-xs-12 col-sm-12 col-md-3">
          <a href="./html/mobileLearning.html" title="mobileLearning" class="thumbnail"><img src="images/school_tablets001-1.jpg" alt="mobileLearning" /></a>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-2">
          <ul class="meta-search">
            <li><i class="glyphicon glyphicon-calendar"></i> <span class="date"></span></li>
            <li><i class="glyphicon glyphicon-time"></i> <span class="time"></span></li>
          </ul>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-7 excerpet">
          <h3><a href="./html/mobileLearning.html" title="mobile Learning">mobile Learning</a></h3>
          <p>Mobile learning solutions from Skymics can open up a world of knowledge – and possibilities.</p>
          <span class="plus"><a href=href="./html/mobileLearning.html" title="mobile Learning"><i class="glyphicon glyphicon-plus"></i></a></span>
        </div>
        <span class="clearfix borda"></span>
      </article>
    </section>
  </div>
  <script src="test.js"></script>

</body>

示例记录器消息处理程序:

class MessageHandler1 : DelegatingHandler
    {


    private int _count = 0;

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        System.Threading.Interlocked.Increment(ref _count);
        request.Headers.Add("X-Custom-Header", _count.ToString());
        return base.SendAsync(request, cancellationToken);
    }
}

}

将其添加到管道

class LoggingHandler : DelegatingHandler

{
    StreamWriter _writer;

public LoggingHandler(Stream stream)
{
    _writer = new StreamWriter(stream);
}

protected override async Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
    var response = await base.SendAsync(request, cancellationToken);

    if (!response.IsSuccessStatusCode)
    {
        _writer.WriteLine("{0}\t{1}\t{2}", request.RequestUri, 
            (int)response.StatusCode, response.Headers.Date);
    }
    return response;
}

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        _writer.Dispose();
    }
    base.Dispose(disposing);
}

线程问题

关于线程问题或并发性,HttpClient client = HttpClientFactory.Create(new Handler1(), new Handler2(), new Handler3()); 方法的HttpRequestMessage参数将按请求进行。如果您将标头添加到SendAsync集合,则只会更新该请求实例的标头(即非全局)

或者使用request.Headers实例上的Authorization属性:

request.Headers

请参阅下面的MSDN链接

https://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage

如果您对HttpClient的静态,共享,单例,Lifestyle.Singleton等实例使用request.Headers.Authorization = new AuthenticationHeaderValue("bearer", bearerToken); ,那么您将遇到线程问题并需要正确同步才能更新DefaultRequestHeaders集合。 / p>