【问题标题】:redirect to actionResult method from an api从 api 重定向到 actionResult 方法
【发布时间】:2015-06-06 19:24:45
【问题描述】:
[HttpPost]
    public void insertData(string productid)
    {
        //insert to db
        string uri = this.Url.Link("Default", new { controller = "AddProducts", action = "Index" });
        //Response.Redirect(Url.Action("", ""));
    }

插入数据库后,我想重定向到 actionResult 方法。我有一个 void 方法,我将它返回为什么?

【问题讨论】:

  • 什么意思?如果您想向浏览器返回结果,只需从您自己的方法中返回一个 ActionResult 并确保在其中放置了足够的数据来呈现您的视图。如果要重定向到另一个 URL,请使用新 URL 返回 302
  • 我的意思是在 api 控制器内。actionResult 只在 mvc 控制器内工作

标签: c# asp.net-mvc-4 asp.net-web-api


【解决方案1】:

这是 MVC 控制器还是 Web Api 控制器?

如果是 MVC:

您必须返回一个 ActionResult 而不是 void。

您的代码将如下所示。

    [HttpPost]
    public ActionResult AddProduct(string productid)
    {
        //Add product to db logic goes here

        return RedirectToAction("{Your parameters here}");
    }

深入了解细节是您的任务。看看这个以了解更多关于 ActionResult - https://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult%28v=vs.118%29.aspx

如果是网络 API:

您只返回 Http 响应消息。 http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results

【讨论】:

  • 重定向意味着响应是带有新 URL 的 302 状态。 RedirectToAction 只是创建适当的 URL。在 Web API 中,只需调用 RedirectRedirectToRoute 方法之一
猜你喜欢
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多