首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过OWIN实现global.asax事件

如何通过OWIN实现global.asax事件
EN

Stack Overflow用户
提问于 2016-03-01 01:35:45
回答 1查看 9.1K关注 0票数 7

在asp.net 6中,不会有名为global.asax的文件,但global.asax有许多事件,如

·Application_Init

·Application_Start

·Session_Start

·Application_BeginRequest

·Application_EndRequest

·Application_AuthenticateRequest

·Application_Error

·Session_End

·Application_End

例如,我经常使用Application_BeginRequest事件来重定向用户。下面是一个示例代码

代码语言:javascript
复制
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吗?

请讨论谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-11 06:51:36

如果您需要在每次请求之前执行一些自定义操作,我建议您使用标准方法:创建一个中间件并将其插入到HTTP请求管道中。

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

代码语言:javascript
复制
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方法中完成的:

代码语言:javascript
复制
public class Startup
{
  public void Configure(IApplicationBuilder app)
  {
    ...
    app.UseMiddleware<MyMiddleware>();
    ...
  }
}

就这样。忘了global.asax吧;-)

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35705830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档