【问题标题】:possible to return a http request from inside an actionResult?可以从 actionResult 中返回 http 请求吗?
【发布时间】:2014-01-30 12:25:39
【问题描述】:

使用 ActionResult:如果一切顺利 return new EmptyResult 如果出现问题 throw an exception。但是,由于并非所有代码路径都返回一个值,我需要在函数底部添加某种return。最好是 http 请求...404。

我想做的是从控制台应用程序运行此功能,并将 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
        }

【问题讨论】:

  • 感谢大家的回答,我决定使用个性化的 msg...return new HttpStatusCodeResult(404, "Error in GetPLUInfo");

标签: c# asp.net asp.net-mvc-3


【解决方案1】:

您可以将 Response.StatusCode 设置为有效的 http 错误,例如:

Response.StatusCode = 500;

然后,您可以让 web.config 中的错误处理来处理要做什么、重定向到您自己的自定义操作或只返回页面。

【讨论】:

    【解决方案2】:

    来源所以

    按照这个post你可以这样返回

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

    【讨论】:

      【解决方案3】:

      你可以试试这个

      catch (Exception)
              {
                  throw;
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-21
        • 1970-01-01
        • 2021-02-21
        • 2021-06-28
        • 2017-02-22
        • 2014-08-01
        • 2018-08-14
        • 1970-01-01
        相关资源
        最近更新 更多