[英]'context.Request' threw an exception of type 'System.Web.HttpException'
[英]'Session' threw an exception of type system.web.httpexception
我試圖在Page_Load
上獲得一個Session["user"]
但它一直給我這個崩潰:
'Session' 拋出了 system.web.httpexception 類型的異常
會話狀態只能在 enableSessionState 設置為 true 時使用,無論是在配置文件中還是在 Page 指令中。 還請確保 System.Web.SessionStateModule 或自定義會話狀態模塊包含在應用程序配置的 \\\\ 部分中。
這是我的 web.config
<configuration>
<system.web>
<pages enableSessionState="true" />
<httpModules>
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
</httpModules>
</system.web>
</configuration>
配置標簽里面還有其他的東西,但重要的部分是這個,配置正確,但錯誤仍然相同。
為什么會這樣?
.aspx 沒什么大不了的
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Session["user"] == null)
Response.Redirect("~/Login.aspx");
}
}
我剛剛遇到了類似的問題,並在所有地方的連字符網站上找到了解決方案。 我的代碼:
void Application_Error(object sender, EventArgs e )
{
Exception ex = Server.GetLastError();
if ( ex != null )
{
if ( ex.GetBaseException() != null )
{
ex = ex.GetBaseException();
}
if ( Session != null ) // Exception occurred here.
{
Session[ "LastException" ] = ex;
}
Toolbox.Log( LogLevel.Error, "An Application Error Occurred", ex );
}
}
...並將指示的行更改為:
if ( HttpContext.Current.Session != null )
代碼現在按我的預期執行。 警告 Emptor:我指向該連字符網站的鏈接在此頁面上的行為與從 Google 結果頁面到我的查詢的行為不同
'session' threw an exception of type 'system.web.httpexception'
您的 web.config 中有 Seesionstate 標簽嗎?嘗試添加此標簽。
樣本:
<sessionState mode="Off|InProc|StateServer|SQLServer"
cookieless="true|false"
timeout="number of minutes"
stateConnectionString="tcpip=server:port"
sqlConnectionString="sql connection string"
stateNetworkTimeout="number of seconds"/>
更多詳情: http : //msdn.microsoft.com/en-us/library/ms178586.aspx
如果您使用的是 win2008 和 IIS,則默認情況下可能不會啟用會話狀態。 您可以檢查 IIS 中是否啟用了Session State Mode Settings
?
這是您要查找的內容的圖片:
右鍵單擊並選擇Open Feature
並確保將其設置為enabled
。
嘗試在頁面指令中設置EnableSessionState="true"
<%@ Page EnableSessionState="true" %>
“ASP.NET 狀態服務”的啟動和停止在類似情況下幫助了我。
Convert.ToString() V/S obj.ToString()
使用 Convert.ToString(),因為如果您使用 obj.ToString() 並且 object(obj) 值為 null,它將引發“System.NullReferenceException”類型的異常。 異常的原因是 null 沒有名為 ToString() 的方法。
Response.Write("名稱:" + Session["User_Name"].ToString()); //這里如果 Session["User_Name"] 為空會拋出異常。
Response.Write("名稱:" + Convert.ToString(Session["User_Name"])); //這里不會拋出任何異常。
參考這個鏈接: http : //burnignorance.com/asp-net-developer-tips/some-best-practices-while-writing-asp-net-code/
我不確定這與多少相關,但我最近為自己創造了這個問題。
在一個較舊的 WebForms 項目中,我已將類的名稱從_Default
更改為[Default]
- 遵循樣式指南。
那是Default.aspx
繼承的 CodeBehind 類——我的 WebForms 應用程序的默認頁面。
我不確定為什么這個名稱會導致 Session 被刪除,但是將其改回_Default
解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.