我正在尝试以下方法:
[System.Web.Http.AcceptVerbs("PUT")]
public HttpResponseMessage MakePost(PostDto post) {
try {
var response = Request.CreateResponse(HttpStatusCode.Redirect); // tried MOVED too
response.Headers.Location = new Uri("google.com");
return response;
} catch (Exception e) {
ErrorSignal.FromCurrentContext().Raise(e);
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎是部分工作 - 当调用它时,我在chrome调试器中看到POST请求."响应"选项卡中没有任何内容,但随后我看到发送到新URI的GET请求,但页面永远不会更改,并且我的AJAX调用会引发错误:
var options = {
url: postUrl,
type: type,
dataType: 'json',
xhrFields: {
withCredentials: true
}
};
return $.ajax(options)
.done(function (response) {
// do stuff
})
.fail(function (response) {
alert('error) // this gets hit - shouldn't the browser have redirected at this point?
}).complete(function () {
// stuff
});
};
Run Code Online (Sandbox Code Playgroud)
如果我检查响应,我看到状态200"OK"......我很困惑.
我究竟做错了什么?
发生这种情况是因为发出AJAX请求的代码遵循重定向,而不是浏览器.这将失败,因为AJAX请求尝试访问其他域.如果要重定向浏览器,则应返回一些JSON结果或自定义HTTP标头,在jQuery中手动选择它,并在那里进行重定向.
在你的控制器中:
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("FORCE_REDIRECT", "http://google.com");
Run Code Online (Sandbox Code Playgroud)
然后为AJAX调用添加成功回调:
success: function(data, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('FORCE_REDIRECT') !== null){
window.location = jqXHR.getResponseHeader('FORCE_REDIRECT');
return;
}
}
Run Code Online (Sandbox Code Playgroud)
在过去,我已将控制器结果包装在自定义操作结果类中以供重用.
归档时间: |
|
查看次数: |
11303 次 |
最近记录: |