2014-01-30 47 views
0

使用ActionResult:如果一切順利return new EmptyResult如果出現問題throw an exception。但是由於並不是所有的代碼路徑都返回一個值,我需要在函數的底部添加某種return。最好是http請求... 404。可能從actionResult中返回一個http請求?

我試圖做的是從控制檯應用程序運行此功能廣告將PLU記錄下載到CSV文件。這一切工作正常,但引發錯誤與「迴歸」 ....任何想法表示歡迎

public ActionResult GetPLUInfo() 
    { 
     try 
     { 
      //CSV FILE of PLUs 
      IEnumerable<PLURecord> listOfPLUs = _pluService.GetAll(); 

      using (StreamWriter outfile = new StreamWriter(@"C:\Users\Martin\Desktop\chocListWRITE.csv", true)) //true: append text to a file with StreamWriter. The file is not erased, but just reopened and new text is added to the end. 
      { 
       foreach (PLURecord _plu in listOfPLUs) 
       { 
        string line = _plu.Serialize(); 
        outfile.WriteLine(line); 
        Console.WriteLine(line); 
       } 

      } 

      HttpContext.ApplicationInstance.CompleteRequest(); 



      return new EmptyResult(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("GetPLUInfo."); 
       Console.WriteLine(ex.Message); 
      } 

      //RETURN: How can i say here to return a http request error, 
      //Using the ActionResult 
     } 
+0

[返回404錯誤ASP.NET MVC 3]的可能重複(http://stackoverflow.com/questions/5635114/returning-404-error-asp-net-mvc-3) – hutchonoid

+0

感謝您的答案傢伙iv決定去與個性化的味精...返回新的HttpStatusC odeResult(404,「GetPLUInfo中的錯誤」); – John

回答

0

您可以將Response.StatusCode設置像一個有效的HTTP錯誤:

Response.StatusCode = 500; 

然後您可以讓web.config中的錯誤處理處理要執行的操作,重定向到您自己的自定義操作或僅返回該頁面。

0

源,以便

按本post可以返回這樣

return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest); 
0

你可以只嘗試這種

catch (Exception) 
     { 
      throw; 
     } 
相關問題