2015-10-07 59 views
-1

我想登錄到我和我的控制檯應用程序MyBB的論壇,但我得到一個錯誤與我的代碼爲「POSTDATA默認參數值必須是一個編譯時常

默認參數值'必須是編譯時常量

如果我將用戶名和密碼設置爲常量字符串,但我無法使用Console.ReadLine();所以我將不得不硬編碼的用戶名和密碼,我不認爲這是一個好主意。

這是我的代碼:

 public string Username = Console.ReadLine(); 
    public string Password = Console.ReadLine(); 
    public const string ForumUrl = "forum.smurfbot.net"; 

    static void Main(string[] args) 
    { 

    } 

    public string MakePostRequest(string url = "www.website.com/usercp.php", string postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login") 
    { 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
     request.KeepAlive = true; 
     request.Method = "POST"; 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.AllowAutoRedirect = true; 

     byte[] postBytes = Encoding.ASCII.GetBytes(postData); 
     request.ContentLength = postBytes.Length; 
     Stream requestStream = request.GetRequestStream(); 
     requestStream.Write(postBytes, 0, postBytes.Length); 
     requestStream.Close(); 

     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     StreamReader sr = new StreamReader(response.GetResponseStream()); 
     string sReturn = sr.ReadToEnd(); 
     sr.Dispose(); 

     return sReturn; 
    } 

回答

1

爲什麼爲它設置一個默認值擺在首位?這不是功能如何工作!

使用單獨的參數並在函數中執行字符串連接。

public string MakePostRequest(string url, string Username, string Password, string ForumUrl) 
{ 
    string postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login" 
    ... 
} 

對於一個名稱爲通用的「MakePostRequest」的方法有一個默認的URL或默認POST數據聽起來很奇怪。

說實話,我希望它只接受POST數據的URL和映射,然後由調用者爲該請求傳遞適當的數據。

0

C#確實允許比常數設置默認的,所以你不能使用域/其他參數。對於url可以,因爲這是一個常數值。 postData的連接字符串是不允許的。

一個選項是將默認設置爲null,並在您的方法中檢查它。這是允許

public string MakePostRequest(string url = "www.website.com/usercp.php", string postData = null) 
{ 
    if (string.IsNullOrEmpty(postData)) 
    { 
     postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login"; 
    } 
相關問題