2016-10-23 16 views
8

特定のクライアントルートがサーバー上で処理されないようにするミドルウェアを作成しようとしています。私はショートASP.NET Core Response.End()?

context.Response.End(); 

との応答をだろう、私はインテリセンスで終了()メソッドが表示されていないカスタムミドルウェアクラスの多くを見ました。どうすれば応答を終了し、httpパイプラインの実行を停止できますか?前もって感謝します!

public class IgnoreClientRoutes 
{ 
    private readonly RequestDelegate _next; 
    private List<string> _baseRoutes; 

    //base routes correcpond to Index actions of MVC controllers 
    public IgnoreClientRoutes(RequestDelegate next, List<string> baseRoutes) 
    { 
     _next = next; 
     _baseRoutes = baseRoutes; 

    }//ctor 


    public async Task Invoke(HttpContext context) 
    { 
     await Task.Run(() => { 

      var path = context.Request.Path; 

      foreach (var route in _baseRoutes) 
      { 
       Regex pattern = new Regex($"({route})."); 
       if(pattern.IsMatch(path)) 
       { 
        //END RESPONSE HERE 

       } 

      } 


     }); 

     await _next(context); 

    }//Invoke() 


}//class IgnoreClientRoutes 
+0

をちょうど ''次の()を呼び出すことはありません。 – SLaks

答えて

8

従来のASP.NETパイプラインがもう存在しないため、もう終了しません。ミドルウェアはパイプラインです。その時点で要求の処理を停止したい場合は、次のミドルウェアを呼び出さずに戻ります。これにより、パイプラインが効果的に停止します。

スタックは巻き戻され、いくつかのミドルウェアはまだレスポンスにデータを書き込むことができますが、あなたはそのアイデアを得ることができます。あなたのコードから、あなたはパイプラインが実行されるのを避けるためにミドルウェアを避けたいと思うようです。

EDIT:コードでこれを行う方法です。

public class Startup 
{ 
    public void Configure(IApplicationBuilder app) 
    { 
     app.Use(async (http, next) => 
     { 
      if (http.Request.IsHttps) 
      { 
       // The request will continue if it is secure. 
       await next(); 
      } 

      // In the case of HTTP request (not secure), end the pipeline here. 
     }); 

     // ...Define other middlewares here, like MVC. 
    } 
} 
+0

コードでどうやったらいいですか? – Geomorillo

+0

私はコードに感謝を見る – Geomorillo

2

終了方法はもうありません。あなたのミドルウェアでは、パイプラインにの次のデリゲートを呼び出すと、次のミドルウェアに行き要求を処理して処理を進めます。それ以外の場合はリクエストを終了します。次のコードは、next.Invokeメソッドを呼び出すサンプルミドルウェアを示しています。省略した場合、応答は終了します。

using System.Threading.Tasks; 
using Microsoft.AspNetCore.Http; 
using Microsoft.Extensions.Logging; 

namespace MiddlewareSample 
{ 
    public class RequestLoggerMiddleware 
    { 
     private readonly RequestDelegate _next; 
     private readonly ILogger _logger; 

     public RequestLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) 
     { 
      _next = next; 
      _logger = loggerFactory.CreateLogger<RequestLoggerMiddleware>(); 
     } 

     public async Task Invoke(HttpContext context) 
     { 
      _logger.LogInformation("Handling request: " + context.Request.Path); 
      await _next.Invoke(context); 
      _logger.LogInformation("Finished handling request."); 
     } 
    } 
} 

コードに戻ってくると、パターンマッチの場合のメソッドから戻ります。

は、詳細については、Microsoftのコアドキュメントからこのドキュメントに見てみましょう:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware