2016-02-29 48 views
1

就没有文件调用的Global.asax但Global.asax中有许多活动,如从asp.net 6如何实现的Global.asax事件被OWIN

·Application_Init

·的Application_Start

·在session_start

·的Application_BeginRequest

·Application_EndRequest

·Application_AuthenticateRequest

·Application_Error事件

·Session_End中

·Application_End

说,例如,我经常跟Application_BeginRequest事件工作,以重定向用户。这里是一个示例代码

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
      if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("content.aspx?content=gm-mdi-diagnostic-tool")) 
      { 
       Response.RedirectPermanent("http://shop.bba-reman.com/product-category/diagnostic-tools/oem-diagnostic-tools/", true); 
      } 
      else if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("content.aspx?content=landrover_rover_t4_testbook_lite_diagnostic_tool_ids")) 
      { 
       Response.RedirectPermanent("http://shop.bba-reman.com/shop/oem-diagnostic-tools/land-rover-t4-mobile/", true); 
      } 
      else if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("content.aspx?content=ford_ids_main_dealer_tool_mazda_jaguar_landrover")) 
      { 
       Response.RedirectPermanent("http://shop.bba-reman.com/product-category/diagnostic-tools/oem-diagnostic-tools/", true); 
      } 
      else if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("content=coda_fuelling_tester_dynamically_measure_fuel_flow_and_pressure_in_situ_under_load")) 
      { 
       Response.RedirectPermanent("http://shop.bba-reman.com/product-category/diagnostic-tools/", true); 
      } 
}    

所以告诉我如何做到这一点与OWIN?与代码示例进行讨论。

也告诉我如何从OWIN class code捕获session start/end or application start or end

欢迎洽谈感谢

+0

与代码示例进行讨论通常是一个糟糕的问题类型 - 您应该先分享您尝试的内容。你会为这类事情写过滤器。 – blowdart

+0

我想知道如何使用owin实现Application_BeginRequest .....任何想法? – Mou

+0

中间件:https://docs.asp.net/en/latest/fundamentals/middleware.html – danludwig

回答

7

如果需要每个请求之前执行一些定制的,我建议你使用的标准方式:创建一个中间件,并在HTTP请求管道插入。

创建中间件有很多方法,但为了清晰和可维护性,创建一个新类是一个不错的选择。这里是一个例子:

public class MyMiddleware 
{ 
    private readonly RequestDelegate next; 

    public MyMiddleware(RequestDelegate next) 
    { 
    this.next = next; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
    this.BeginInvoke(context); 
    await this.next.Invoke(context); 
    this.EndInvoke(context); 
    } 

    private void BeginInvoke(HttpContext context) 
    { 
    // Do custom work before controller execution 
    } 

    private void EndInvoke(HttpContext context) 
    { 
    // Do custom work after controller execution 
    } 
} 

接下来只剩下注册中间件。这是在Startup类的Configure方法中完成的:

public class Startup 
{ 
    public void Configure(IApplicationBuilder app) 
    { 
    ... 
    app.UseMiddleware<MyMiddleware>(); 
    ... 
    } 
} 

就是这样。并忘记global.asax ;-)

+0

有没有办法处理会话开始和结束与owin中间件....如果可能可以与代码讨论。 – Thomas

+2

对于OWIN中无法处理的许多事件,例如会话事件和非OWIN异常处理,仍然需要Global.asax。 – Dai

相关问题