c# - 从 APIController 操作重定向到其他 MVC Controller 操作

标签 c# asp.net-mvc

我创建了一个具有注册操作的 web api Controller :

public class MyProjApiController : ApiController
    {
        public IHttpActionResult Register()
        {
            return  RedirectToAction("Register", "AccountController"); //??
        }
    }

我正在尝试重定向到 MVC Controller 中的另一个操作 public class AccountController : Controllerpublic async Task<ActionResult> Register(RegVM model)但我在 MyProjApiController 中注册操作有IHttpActionResult AccountController 中的返回类型和注册有 Task<ActionResult> type - 怎么调用它?

最佳答案

我认为您在这里混淆了两个概念。您的 API Controller 应该具有将从某些客户端调用的端点,并且您应该以客户端可以读取的格式(XML 或 JSON)返回一些数据。您不应该重定向到另一个 MVC Controller 。

您应该做的是返回一些数据,这些数据具有客户端可以使用的 MVC 操作 Controller 的路径。

public HttpResponseMessage Register()
{
   //DO something as you want 
    var newUrl = this.Url.Link("Default", new { Controller = "Account", 
                                                Action = "Register" });
    return Request.CreateResponse(HttpStatusCode.OK,
                             new {Success = true, RedirectUrl = newUrl});
}

这将向调用者返回这样的响应,响应状态代码为 200 OK

{
   "Success" : true,
   "RedirectUrl" : "yoursite.com/Account/Register"    
}

客户应该阅读这个并做必要的事情。例如,如果您从您的 js 代码调用此 API,您可以简单地使用 window.location.href 将用户重定向到新页面。

例如,

$.post("PathToYourApiEndpoint",function(res){
  if(res.Success)
  {
    window.location.href = res.RedirectUrl;
  }
}); 

同样,我不确定您为什么首先调用 API 并将用户重定向到 MVC Controller 操作。无论您在 Web api 操作方法中执行什么逻辑,您都可以在 MVC Controller 中执行,从而避免 API 调用。

关于c# - 从 APIController 操作重定向到其他 MVC Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33548370/

相关文章:

c# - 为什么datagridview不刷新?

c# - ASP .NET Core 2.0 中的自记录 REST 服务

C# COM 服务器 - 在 C++ 中测试

c# - 将一段文本绘制到控制台中的某个位置?

asp.net-mvc - 在App_Code中的共享@helper中使用@Html

c# - SaveChanges 在 for 循环中引发验证错误

javascript - 使用 JS/jQuery 在前端对 HTML div 进行排序

c# - Caliburn Micro MVVM : Handling data exchange from one View/ViewModel to other ones

ajax - 识别 ASP.NET MVC 代码中的 Angular js AJAX 调用

javascript - 使用网络摄像头捕捉图像