Global.asax魔术功能

时间:2014-02-08 13:32:05

标签: c# asp.net asp.net-mvc error-handling

在Visual Studio中创建ASP.NET Mvc项目时,Global.asax&将创建Global.asax.cs。在此.cs文件中,您将找到标准的Application_Start方法。

我的问题如下,如何调用此函数?因为它不是覆盖。所以我的猜测是这个方法名称是按照惯例。 Application_Error方法也是如此。

我想知道这些方法的钩子在哪里。因为我编写这些方法(不覆盖它们),我在MSDN中找不到任何关于它们的文档。 (我找到了this页面,但它只是告诉您挂钩Error事件并显示Application_Error(object sender, EventArgs e),但不显示事件和方法的关联方式。)

//Magicly called at startup
protected void Application_Start() 
{
    //Omitted
}

//Magicly linked with the Error event
protected void Application_Error(object sender, EventArgs e)
{
    //Omitted
}

3 个答案:

答案 0 :(得分:15)

它并不是真正神奇的...... ASP.NET管道将所有这些都连接起来。

你可以see the documentation regarding this here

具体来说,您将对以下部分感兴趣:

  

为请求分配了HttpApplication个对象。

由触发的事件列表和按什么顺序组成。

该页面上有链接(此处包含的内容太多),链接到包含更多信息的各种其他页面。


  

ASP.NET自动将应用程序事件绑定到处理程序中   Global.asax文件使用命名约定Application_event等   为Application_BeginRequest。这类似于ASP.NET的方式   页面方法自动绑定到事件,例如页面   Page_Load事件。

来源http://msdn.microsoft.com/en-us/library/ms178473.aspx 功能

答案 1 :(得分:2)

为了揭开已接受答案的“魔力”的神秘面纱,ASP.Net管道将[Route("{orderId:guid}/order-lines/{orderlineId:guid}")] [HttpDelete] public async Task<IActionResult> DeleteOrderLine(Guid orderId, Guid orderLineId) { var request = new DeleteOrderLineRequest(orderLineId); var response = await _mediator.Send(request); var orderLineModel = _mapper.Map<OrderLineDto, OrderLineModel>(response.OrderLine); return Ok(orderLineModel); } 事件自动绑定到类中HttpApplication的方法。如果(很像我)你宁愿看到明确绑定到处理程序的事件,可以通过覆盖Application_EventName绑定它们,Visual Studio将生成具有正确签名的处理程序方法。

HttpApplication.Init()

有一个example of this method of binding events

答案 2 :(得分:1)

ASP.Net本身创建它。以下是根据MSDN的流程 -

  • 用户从Web服务器请求应用程序资源。
  • ASP.NET收到应用程序的第一个请求。
  • 为每个请求创建ASP.NET核心对象。
  • 将HttpApplication对象分配给请求。在此步骤中,将处理Global.asax并自动关联事件。
  • 请求由HttpApplication管道处理。在此步骤中,将引发HttpApplication Global事件。

Here is the reference - ASP.Net Application Life Cycle.

从引用 - ASP.NET使用命名约定Application_event(例如Application_BeginRequest)自动将应用程序事件绑定到Global.asax文件中的处理程序。

相关问题