1

我想要达到的目标:

  1. 每个视图完成执行后,我想对外部合作伙伴进行单独的 http 调用。

  2. 我需要将视图的内容之一作为该 http 调用的正文传递。

到目前为止我所拥有的:

我有一个基本控制器,我的所有控制器都从该控制器继承。

我发现我可以覆盖基本控制器的 onActionExecuted() 方法并在那里编写我的伙伴 http 调用代码,以便在每个操作之后执行它。

在阅读了Send asp.net mvc action result inside email的文章后,我写了一个自定义结果。这使我能够获取视图的内容。(它是另一个控制器的一部分,它也继承自基本控制器)。

我无法弄清楚:

  1. 如何调用控制器操作(将为 http 调用主体呈现内容的操作)以获取基本控制器 onActionExecuted() 方法中的内容?

阿尼尔

4

3 回答 3

1

这将从同一个控制器中的第一个控制器动作中调用第二个控制器动作:

    public ActionResult FirstAction()
    {
        // Do FirstAction stuff here.
        return this.SecondAction(ArgumentsIfAny);
    }

    public ActionResult SecondAction()
    {
        // Do SecondAction stuff here.
        return View();
    }

不需要太复杂。:-)

于 2009-11-12T01:54:53.153 回答
0

大多数 MVC 框架的想法是让事情变得更简单。一切都分解为对具有某些输入和某些返回值的方法的调用。在某种程度上,您可以通过执行以下操作来完成您想要的:

class MyController {
  public ActionResult Action1() {
    // Do stuff 1
  }

  public ActionResult Action2() {
    // Do stuff 2
  }
}

然后你可以重构一下:

class MyController {
  public ActionResult Action1() {
    // Pull stuff out of ViewData

    DoStuff1(param1, param2, ...);
  }

  public ActionResult Action2() {
    DoStuff2(param1, param2, ...);
  }

  public void DoStuff1(/* parameters */) {
    // Do stuff 1
  }

  public void DoStuff2(/* parameters */) {
    // Do stuff 2
  }
}

现在您可以直接调用 DoStuff1() 和 DoStuff2() 因为它们只是方法。如果可能,您可以将它们设为静态。不要忘记您可能需要对错误检查和返回类型做一些事情。

于 2009-03-03T22:24:56.393 回答
0
 protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

            this.ViewData.Model = GLB_MODEL;
            Stream filter = null;
            ViewPage viewPage = new ViewPage();
            viewPage.ViewContext = new ViewContext(filterContext.Controller.ControllerContext, new WebFormView("~/Views/Customer/EmailView.aspx", ""), this.ViewData, this.TempData);
            var response = viewPage.ViewContext.HttpContext.Response;
            response.Clear();
            var oldFilter = response.Filter;

            try
            {
                filter = new MemoryStream();
                response.Filter = filter;

                viewPage.ViewContext.View.Render(viewPage.ViewContext, viewPage.ViewContext.HttpContext.Response.Output);
                response.Flush();

                filter.Position = 0;
                var reader = new StreamReader(filter, response.ContentEncoding);
                string html = reader.ReadToEnd();
            }
            finally
            {
                if (filter != null)
                {
                    filter.Dispose();
                }
                response.Filter = oldFilter;
            }

    }

这是Render a view as a string中代码的修改版本。我不想将视图的结果呈现给 httpcontext 响应流。

于 2009-03-05T00:46:51.443 回答