c# - 在 ActionResult 方法中抛出异常

标签 c# asp.net-mvc web-services exception soap

我有一个带有上传 Controller 的 View ,它会触发此 ActionResult:

    [HttpPost]
    public ActionResult ProcessSubmitUpload(HttpPostedFileBase attachments, Guid? idDocument)
    {
          //Validations
          var xmlDocument = XDocument.Load(attachments.InputStream);
          DocumentCommonHelper.SendFile(xmlDocument);
    }

SendFile 方法:

  public static void SendCte(XDocument xmlDocument)
  {
       var client = new WsSoapClient();
       client.InsertXML(xmlDocument);
  }

如果出现问题,Web 服务将返回 SoapException,例如: “IDDocument 不存在”等等

但是在 MVC 中,当我调试时,如果 InsertXml 方法中出现问题,我无法捕获它,调试导航只会停止并抛出上传文件错误。

我想在我的操作中捕获 InsertXML 方法的返回消息,并将其返回到我的 View 。就像一个“警报”弹出窗口。 我怎样才能做到这一点?

最佳答案

您可以将错误消息返回到 ModelState 对象中的 View 。该 View 可以使用 ValidationSummary 帮助器显示它:

[HttpPost]
public ActionResult ProcessSubmitUpload(HttpPostedFileBase attachments, Guid? idDocument)
{
      //Validations
      var xmlDocument = XDocument.Load(attachments.InputStream);
      try
      {
          DocumentCommonHelper.SendFile(xmlDocument);
      }
      catch(Exception ex)
      {
          ModelState.AddModelError("ProcessSubmitUpload", ex.Message);
          return View(new MyViewModel())
      }
}

查看:

@using(Html.BeginForm("ProcessSubmitUpload", "MyController", FormMethod.Post))
{
    @Html.ValidationSummary()
    ... etc.
}

关于c# - 在 ActionResult 方法中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20570699/

相关文章:

c# - 重写 C# 的绘制方法

c# - 在 WPF 应用程序中找不到资源字典

c# - 文档中 API 方法的分组 - 是否有一些自定义属性

c# - User.IsInRole() 在角色分配后不工作,但在重新登录后工作

python - 如何将下面的示例代码变成接受多个输入?

SQL CLR 存储过程和 Web 服务

c# - HttpListener 如何提供图像

asp.net-mvc - 使 ASP.NET MVC 3 Razor View Engine 忽略 .vbhtml 文件

asp.net-mvc 功能 - 每个( View /母版页/用户控件)一个 css 文件

java - 配置 Spring Web 服务以接受内容类型 text/xml Soap 1.2 消息