2017-09-09 24 views
0

私は、OWINを使用してコンソールアプリケーションで小さなWebアプリケーションを自己ホストします。Owinの同時リクエストの最大数

登録単一のミドルウェアがありますApiControllerに到達する前に:

public class HealthcheckMiddleware : OwinMiddleware 
{ 
    private readonly string DeepHealthEndpointPath = "/monitoring/deep"; 
    private readonly string ShallowHealthEndpointPath = "/monitoring/shallow"; 

    public HealthcheckMiddleware(OwinMiddleware next) 
     : base(next) 
    { 
    } 

    public async override Task Invoke(IOwinContext context) 
    { 
     try 
     { 
      string requestPath = context.Request.Path.Value.TrimEnd('/'); 
      if (requestPath.Equals(ShallowHealthEndpointPath, StringComparison.InvariantCultureIgnoreCase) 
       || requestPath.Equals(DeepHealthEndpointPath, StringComparison.InvariantCultureIgnoreCase)) 
      { 
       context.Response.StatusCode = (int) HttpStatusCode.OK; 
      } 
      else 
      { 
       await Next.Invoke(context); 
      } 
     } 
     catch (Exception ex) 
     { 
      // This try-catch block is inserted for debugging 
     } 
    } 
} 

ここNext.Invokeは基本的に非同期的に別のAPIにHTTPリクエストを転送コントローラメソッドを呼び出す、関心のメインライン、すなわち:

var response = await _httpClient.SendAsync(outgoingRequest); 

しかし、私はこのようなAPI

(私はAPIにpreassureを入れたいような目的にそれらを待っていない)に10件のhttpリクエストを提出しようとした場合
for (int i = 0; i < 10; i++) 
{ 
    var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5558/forwarder"); 
    httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json"); 
    httpClient.SendAsync(httpRequestMessage); 
} 

、その後、直後に10以上を提出し、その後、私はHealthcheckMiddlewareでcatchブロックで、次の例外を取得:

と、InvalidOperationException:応答が送信された後に、この操作を行うことができません。

スタックトレース:私はstackoverflowのとGoogleの両方を検索しようとしましたが、価値のあるものを見つけることができないよう

at System.Net.HttpListenerResponse.set_ContentLength64(Int64 value) 
at Microsoft.Owin.Host.HttpListener.RequestProcessing.ResponseHeadersDictionary.Set(String header, String value) 
at Microsoft.Owin.Host.HttpListener.RequestProcessing.HeadersDictionaryBase.Set(String key, String[] value) 
at Microsoft.Owin.Host.HttpListener.RequestProcessing.HeadersDictionaryBase.set_Item(String key, String[] value) 
at Microsoft.Owin.HeaderDictionary.System.Collections.Generic.IDictionary<System.String,System.String[]>.set_Item(String key, String[] value) 
at System.Web.Http.Owin.HttpMessageHandlerAdapter.SetHeadersForEmptyResponse(IDictionary`2 headers) 
at System.Web.Http.Owin.HttpMessageHandlerAdapter.SendResponseMessageAsync(HttpRequestMessage request, HttpResponseMessage response, IOwinResponse owinResponse, CancellationToken cancellationToken) 
at System.Web.Http.Owin.HttpMessageHandlerAdapter.<InvokeCore>d__0.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
at DataRelay.NonGuaranteedDataForwarder.HealthcheckMiddleware.<Invoke>d__3.MoveNext() in C:\_code\DataRelay.NonGuaranteedDataForwarder\HealthcheckMiddleware.cs:line 30 

。たとえば、私はthisを見つけましたが、ここでは開発者はリクエストを送信した後にそれを読んでいますが、私はしません。

は、念のためにそれがApiControllerで完全なPOSTメソッドがここに含まれている興味がある可能性があり:

public async Task<HttpResponseMessage> Post(HttpRequestMessage request) 
    { 
     try 
     { 
      MetricCollector.RecordIncomingRecommendation(); 
      using (MetricCollector.TimeForwardingOfRequest()) 
      { 
       string requestContent = await request.Content.ReadAsStringAsync().ConfigureAwait(false); 
       var data = JObject.Parse(requestContent); 
       string payloadType = data.SelectToken("Headers.PayloadType").ToString(); 
       Log.Logger.Debug("Received message containing {PayloadType}", payloadType); 

       var consumersForPayloadType = _consumers.Where(x => x.DataTypes.Contains(payloadType)).ToList(); 
       if (consumersForPayloadType.Any()) 
       { 
        Log.Logger.Debug("{NumberOfConsumers} interested in {PayloadType}", 
         consumersForPayloadType.Count, 
         payloadType); 
       } 
       else 
       { 
        Log.Logger.Warning("No consumers are interested in {PayloadType}", payloadType); 
       } 

       foreach (var consumer in consumersForPayloadType) 
       { 
        try 
        { 
         var outgoingRequest = new HttpRequestMessage(HttpMethod.Post, consumer.Endpoint); 
         outgoingRequest.Content = new StringContent(requestContent, Encoding.UTF8, 
          "application/json"); 

         foreach (var header in request.Headers) 
         { 
          if (IsCustomHeader(header, _customHeaders)) 
           outgoingRequest.Headers.Add(header.Key, header.Value); 
         } 

         if (!string.IsNullOrWhiteSpace(consumer.ApiKey)) 
         { 
          request.Headers.Add("Authorization", "ApiKey " + consumer.ApiKey); 
         } 

         var response = await _httpClient.SendAsync(outgoingRequest); 
         if (!response.IsSuccessStatusCode) 
         { 
          Log.Logger.ForContext("HttpStatusCode", response.StatusCode.ToString()) 
           .Error("Failed to forward message containing {PayloadType} to {ConsumerEndpoint}", 
            payloadType, consumer.Endpoint); 
         } 
        } 
        catch (Exception ex) 
        { 
         MetricCollector.RecordException(ex); 
         Log.Logger.Error(ex, 
          "Failed to forward message containing {PayloadType} to {ConsumerEndpoint}", payloadType, 
          consumer.Endpoint); 
        } 
       } 

       return request.CreateResponse(HttpStatusCode.OK); 
      } 
     } 
     catch (Exception ex) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, ex); 
     } 
    } 

答えて

0

はどこにでも.ConfigureAwait(false)を削除してみて、それが助けかどうかを確認します。

など。ここに:

string requestContent = await request.Content.ReadAsStringAsync().ConfigureAwait(false); 

UPD1:[OK]をクリックします。ストレステストに異なるクライアントを使用する場合、サーバーでこの例外が発生するかどうかを確認してください。たとえば、this oneです。 httpClient.SendAsync(...);をお待ちしていないあなたのアイデアは非常に独特です。

+0

残念ながら、それは何の違いもありませんでした。しかし、提案に感謝! – SabrinaMH

関連する問題