2012-08-07 44 views
0

我做了一些asp編程,但沒有使用asp.net或aspx腳本。 我想創建一個腳本,如果cookie沒有設置,它將發送一個html文件,但如果是的話發送一個pdf文件。我不斷收到一個運行時錯誤。asp.net c#aspx if statements not working

這裏是我的代碼:

<%@ Page Language="C#" %> 
<% 
HttpCookie mycookie = Request.Cookies["CHECK"]; 
if (mycookie.Value == ""){ 
Response.ContentType = "text/html"; 
Response.Clear(); 
Response.TransmitFile("forbidden.html"); 
Response.End(); 
} 
else 
{ 
Response.ContentType = "application/pdf"; 
Response.Clear(); 
Response.TransmitFile("test.pdf"); 
Response.End();   
} 
%> 

我已經測試了HTML和PDF和都工作得不錯的響應代碼塊和文件發送到瀏覽器。我添加了設置mycookie和cookie信息的行,它仍然有效。當我添加if邏輯時,出現運行時錯誤。

有人能告訴我我做錯了什麼嗎?

在此先感謝您的幫助。

+0

什麼錯誤? – Magrangs 2012-08-07 14:26:08

+0

未將對象引用設置爲對象的實例。 – tjd 2012-08-07 14:39:21

回答

1

如果Cookies["CHECK"]未設置,則mycookie將爲null。因此你可能會得到一個NullReferenceException

嘗試以下操作:

if (mycookie == null || String.IsNullOrEmpty(myCookie.Value))) { 
    // ... 
} else { 
    // ... 
} 

,歡迎#1。

+0

我添加了這一行,它給了我:錯誤CS0117:'string'不包含'IsNullOrEmpty'的定義 – tjd 2012-08-07 14:38:14

+0

請使用帶有大寫字母'S'的'String'重試。 – 2012-08-07 14:39:30

+0

我不知道downvote是什麼。 – 2012-08-07 14:42:46

0

您需要檢查mycookie是否爲空。

嘗試類似:

if (mycookie == null || String.IsNullOrEmpty(mycookie.Value)){ 
+0

其實,你的第一個答案是錯誤的,你沒有驗證myCookie爲null ...那麼爲什麼-1? – 2012-08-07 14:36:52

+0

@丹尼斯,雖然這是一個不必要的答案,但沒有必要粗魯 – freefaller 2012-08-07 14:37:15

+0

@freefaller真。抱歉。將刪除我的評論,但保留-1BrunoCosta -1 – 2012-08-07 14:37:49

-1

我的意思是,更好的是:

<%@ Page Language="C#" %> 
<% 
HttpCookie mycookie = Request.Cookies["CHECK"]; 
if ((mycookie != null) && (mycookie.Value == "")) { 
Response.ContentType = "text/html"; 
Response.Clear(); 
Response.TransmitFile("forbidden.html"); 
Response.End(); 
} 
else 
{ 
Response.ContentType = "application/pdf"; 
Response.Clear(); 
Response.TransmitFile("test.pdf"); 
Response.End();   
} 
%> 
+0

這可能會做錯事。如果Request.Cookies [「CHECK」]評估爲「null」,它將執行else塊。 – 2012-08-07 14:44:23