[英]'Session' threw an exception of type system.web.httpexception
[英]'context.Request' threw an exception of type 'System.Web.HttpException'
我正在嘗試在 Global.asax Application_Start() 事件中使用訪問 HTTPContext。
var context = HttpContext.Current;
if (context != null)
{
if (context.Request != null) //Getting error here
{
.....
}
}
訪問context.Request
我收到'context.Request' threw an exception of type 'System.Web.HttpException'
異常'context.Request' threw an exception of type 'System.Web.HttpException'
異常。
在這種情況下context.Request
不是 null 而是它拋出的異常。
我使用以下代碼來確定Request
屬性是否存在:
context.GetType().GetProperty("Request");
我得到了以下回應。
{System.Web.HttpRequest Request}
Attributes: None
CanRead: true
CanWrite: false
CustomAttributes: Count = 0
DeclaringType: {Name = "HttpContext" FullName = "System.Web.HttpContext"}
GetMethod: {System.Web.HttpRequest get_Request()}
IsSpecialName: false
MemberType: Property
MetadataToken: 385876876
Module: {System.Web.dll}
Name: "Request"
PropertyType: {Name = "HttpRequest" FullName = "System.Web.HttpRequest"}
ReflectedType: {Name = "HttpContext" FullName = "System.Web.HttpContext"}
SetMethod: null
I am not sure how to confirm if context.Request exists and is not null ?
從文檔:
如果您在 HttpRequest 對象不可用時嘗試使用此屬性,則 ASP.NET 將引發異常。 例如,這在 Global.asax 文件的 Application_Start 方法中或在從 Application_Start 方法調用的方法中是正確的。 當時還沒有創建 HTTP 請求。
Application_Start
並不意味着處理特定請求,因此您需要將您正在執行的操作移動到不同事件的處理程序中,例如BeginRequest
。
public class Global : HttpApplication
{
private static HttpRequest initialRequest;
static Global()
{
initialRequest = HttpContext.Current.Request;
}
void Application_Start(object sender, EventArgs e)
{
//access the initial request here
}
您可以在此處使用 Application_Start 事件。靜態類型是使用其 HTTPContext 中的請求創建的,允許您存儲它並立即在 Application_Start 事件中重用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.