c# - 在 ASP .NET MVC 中的 Controller 之间共享数据的最佳方法是什么?

标签 c# asp.net-mvc

我有两个 Controller :

public class AController : Controller
{
      public ActionResult AControllerAction()
      {
          if (// BControllerAction reported an error somehow )
          {
                ModelState.AddModelError("error-key", "error-value");
          }
          ...
      }
}

public class BController : Controller
{
      public ActionResult BControllerAction()
      {
          try{Something();}
          catch(SomethingExceprion)
          {
              // here I need to add error info data,
              // pass it to AController and redirect to
              // AControllerAction where this error will be added 
              // to model state
          }
      }
}

我想我可以这样做:

public ActionResult BControllerAction()
{
     try{Something();}
     catch(SomethingException)
     {
         var controller = new AController();
         controller.ModelState.AddModelError("error-key", "error-value");
         controller.AControllerAction();
     }
}

但我建议这将是一种破坏架构的方法,我不想那样做。除了传递模型对象之外,还有更简单、更安全的方法吗?

最佳答案

根据您需要传回 Controller A 的异常细节,我会按照以下方式做一些事情

public ActionResult BControllerAction()
{
     try{Something();}
     catch(SomethingException ex)
     {
         return RedirectToAction("AControllerAction", "AController", new { errorMessage = ex.Message() })
     }
}

然后把被调用方法的签名改成

public ActionResult AControllerAction(string errorMessage)
      {
          if (!String.IsNullOrEmpty(errorMessage))
          {
                //do something with the message
          }
          ...
      }

关于c# - 在 ASP .NET MVC 中的 Controller 之间共享数据的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199379/

相关文章:

.net - 将 CasTLe Windsor 与 SignalR 集成 - 我应该如何处理这个问题?

c# - 如何在 C# 中获取 session ID

c# - Linux 中的 MonoDevelop——终端命令

c# - 我得到 "missing a using directive or assembly reference"并且不知道出了什么问题

c# - 可选嵌套?这个语言功能叫什么,它的用途是什么?

c# - 使用 MVC 5 和 Entity Framework 下拉关联实体

c# - 为什么在使用 XMPP 时,多次聊天发送时会收到 'service unavailable'?

asp.net-mvc - 如何告诉 MVC 在 Asp.net MVC 中的上一个类之后追加 ".input-validation-error"类

jquery - MVC 4 自定义数据注解手动jquery验证调用

asp.net-mvc - 在依赖解析器内核中找不到 BindFilter 方法