Web API重定向以使用模型进行查看 [英] Web API redirect to view with model

查看:54
本文介绍了Web API重定向以使用模型进行查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从api方法重定向到具有某些模型的某些View?就像在标准控制器中一样:

How can I redirect from api method to some View with some model? This is as in the standart controller:

return RedirectToAction("View",model).

我可以在ApiController的方法中做类似的事情吗?

Can I make something like this in a method of ApiController?

推荐答案

您通常使用AJAX调用Web API.例如,使用jQuery $.getJSON .

You usually invoke Web API using AJAX. For example using jQuery $.getJSON.

所有AJAX请求均由浏览器的 XMLHttpRequest 对象处理.如果此对象收到 redirect 响应,则只需将AJAX调用重复到给定的URL.这是在透明的情况下发生的,即 XHR 对象不会以任何方式通知它已完成重定向,因此您无法以任何方式检测到它.

All the AJAX request are handled by the XMLHttpRequest object of the browser. If this object receives a redirect response, it simply repeats the AJAX call to the given URL. That happens trasnparently, i.e. the XHR object doesn't notify in any way that it has done a redirect, so you cannot detect it in any way.

因此,简短的答案是您不能通过AJAX调用在浏览器中引发重定向:无论是Web API还是MVC或传统的Web窗体都没有关系,问题始终是 XHR 隐藏重定向响应,它仅在内部使用它.

So, the short answer is that you cannot provoke a redirect in the browser via an AJAX call: it doesn't matter if it's Web API or MVC or traditional Web Forms, the problem is always that the XHR hides the redirects response, it simply uses it internally.

长答案是,您可以向客户端发送特殊响应,例如可以在JavaScript AJAX客户端中识别的对象,并使用传统的 window.location.href = * newUrl * 强制在客户端上进行重定向.

The long answer is that you can send an special response to the client, for example an object that can be recognized in the JavaScript AJAX client and use the traditional window.location.href=*newUrl* to force the redirect on the client.

例如,您可以实现这样的Web API方法

For example you could implement a Web API method like this

public object GetRedirection()
{
   return new {
     redirect = true,
     newUrl = 'http://www.stackoverflow.com'
   };
}

然后调用它并检查结果,例如,以这种方式:

And then invoke it and check the result, for example in this way:

$.getJSON('http://..../MyControler').done(function(result) {
  if (result.redirect) {
    window.location.href = result.newUrl;
  }
})

这是强制使用AJAX客户端(即间接)重定向的唯一方法.

This is the only way to force a redirect with an AJAX client, i.e. indirectly.

注意:当然,如果在浏览器地址栏中键入Web API的URL,并且调用的操作返回重定向响应,它将重定向浏览器.但是我确实假设您正在将Web API与AJAX结合使用.您还可以做一个奇怪的事情:使用相同的 window.location.href 代码调用返回重定向的Web API操作.

NOTE: of course, if you type the URL of the Web API in the browser address bar, and the invoked action returns a redirect response, it will redirect the browser. But I do suppose that you're using Web API with AJAX. You could also do a strange thing: use the same window.location.href code to invoke the Web API action that returnt the redirect.

这篇关于Web API重定向以使用模型进行查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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