简体   繁体   English

将数据从 WebApi 控制器传递到 MVC 控制器

[英]Passing data from a WebApi Controller to an MVC Controller

I have data coming in to a WebApi controller which gets converted into ac# object, and I need to pass this to an MVC controller, at the moment I am holding this object in a static "Globals" class and then assigning an instance of my ViewModel to that object in my MVC controller which then returns as usual.我有数据进入 WebApi 控制器,该控制器被转换为 ac# 对象,我需要将其传递给 MVC 控制器,目前我将此对象保存在静态“Globals”类中,然后分配我的实例ViewModel 到我的 MVC 控制器中的那个对象,然后像往常一样返回。 I'm aware of using TempData to pass data between MVC controllers.我知道使用 TempData 在 MVC 控制器之间传递数据。 Is there a method to pass data between an APIController and an MVC controller?有没有一种方法可以在 APIController 和 MVC 控制器之间传递数据? (I'm not using a database). (我没有使用数据库)。

Here is the action in my APIController which gets the message by an external device:这是我的 APIController 中的操作,它通过外部设备获取消息:

    [Route("someroute"), HttpPost]
    public IHttpActionResult Post([FromBody] object obj)
    {
        try
        {

            MessageViewModel model = new MessageViewModel();
            model.Object = obj;
            Globals.model = model;
            return Ok();
        }
        catch
        {
            return BadRequest();
        }
    }

I need to pass that model to my MVC controller.我需要将该模型传递给我的 MVC 控制器。 At the moment I am storing it in a static class and then my MVC controller:目前我将它存储在一个静态类中,然后是我的 MVC 控制器:

    public ActionResult Index()
    {
        return View(Globals.model);
    }

Is returning it when a client calls the action.当客户端调用操作时返回它。

@peco is absolutely correct, you need to move logic outside mvc controller and reuse it in web api. @peco 是绝对正确的,您需要将逻辑移到 mvc 控制器之外并在 web api 中重用它。 If for some reason you cant do this, what preventing you from redirect with necessary parameters?如果由于某种原因你不能这样做,是什么阻止你使用必要的参数重定向?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM