将数据从WebApi控制器传递到MVC控制器 [英] Passing data from a WebApi Controller to an MVC Controller

查看:81
本文介绍了将数据从WebApi控制器传递到MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据输入到WebApi控制器中,该控制器被转换为ac#对象,现在我需要将此数据传递给MVC控制器,此时我将该对象保存在静态的"Globals"类中,然后分配一个我的MVC控制器中该对象的ViewModel实例,该对象随后照常返回.我知道使用TempData在MVC控制器之间传递数据.有没有一种方法可以在APIController和MVC控制器之间传递数据?(我没有使用数据库).

I have data coming in to a WebApi controller which gets converted into a c# 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. I'm aware of using TempData to pass data between MVC controllers. Is there a method to pass data between an APIController and an MVC controller? (I'm not using a database).

这是我的APIController中的操作,该操作通过外部设备获取消息:

Here is the action in my APIController which gets the message by an external device:

    [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();
        }
    }

我需要将该模型传递给我的MVC控制器.目前,我将其存储在静态类中,然后存储在我的MVC控制器中:

I need to pass that model to my MVC controller. At the moment I am storing it in a static class and then my MVC controller:

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

当客户调用操作时将其返回.

Is returning it when a client calls the action.

推荐答案

@peco是绝对正确的,您需要将逻辑移到mvc控制器之外,并在Web api中重用它.如果由于某些原因您无法执行此操作,那么是什么导致您无法使用必要的参数进行重定向?

@peco is absolutely correct, you need to move logic outside mvc controller and reuse it in web api. If for some reason you cant do this, what preventing you from redirect with necessary parameters?

这篇关于将数据从WebApi控制器传递到MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆