2017-03-16 55 views
0

我已经做了一些零件在启动等中间件..迁移到核心,但那些困于旧“模块”(HttpApplication的)

所以这是我的课

public class AcceptQueryMiddleware 
    { 
     private const string Realm = "Basic realm=My Sales System"; 
     private readonly RequestDelegate _next; 

     private static readonly IDictionary<Regex, string> FormatAcceptMap = new Dictionary<Regex, string>(); 

     public AcceptQueryMiddleware(RequestDelegate next) 
     { 
      _next = next; 
     } 
     public void AcceptQueryHttpModule() 
     { 
      RegisterFormatAcceptQuery("csv", "text/csv"); 
      RegisterFormatAcceptQuery("excel", "application/vnd.ms-excel"); 
      RegisterFormatAcceptQuery("nav", "application/navision"); 
     } 

     private static void RegisterFormatAcceptQuery(string format, string acceptHeader) 
     { 
      var regex = new Regex(@"([?]|[&])format=" + format); 
      FormatAcceptMap.Add(regex, acceptHeader); 
     } 

     private static void OnApplicationBeginRequest(object sender, EventArgs eventArgs) 
     { 
      var app = sender as HttpApplication; 
      if (app == null) { return; } 

      var url = app.Request.RawUrl; 
      foreach (var format in FormatAcceptMap) 
      { 
       if (format.Key.Match(url).Success) 
       { 
        app.Request.Headers["Accept"] = format.Value; 
        break; 
       } 
      } 
     } 

     public void Dispose() 
     { 
     } 
    } 

我如何把它转换成Core?绕过它吗? 特别是在.NET Core中不支持的HttpApplication ..

或者您有任何可以关注的链接或提示吗?

回答

0

你想你的HTTP模块迁移到中间件。了解如何参阅documentation

在你的情况,你使用的HttpApplication访问请求相关的数据。您正在获取原始网址并添加一些标题。这是东西,你可以easily在中间件做。这里有一个例子:

public class AcceptQueryMiddleware 
    { 
     private readonly RequestDelegate _next; 

     public AcceptQueryMiddleware(RequestDelegate next) 
     { 
      _next = next; 
     } 

     public async Task Invoke(HttpContext context) 
     { 
      // Do your "before" stuff here (use the HttpContext) 

      await _next.Invoke(context); 

      // Do your "after" stuff here 
     } 
    } 
Startup

,并呼吁app.UseMiddleware<AcceptQueryMiddleware>();(在Configure方法)。

+0

我已经这样做过,但不知何故,我做我的课有点从这个中间件不同。我会回到以前的样子!谢谢 – KakaMir