加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – WebAPI重定向不起作用?

发布时间:2020-12-16 09:25:36 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试以下方法: [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("goo
我正在尝试以下方法:

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

这似乎是部分工作 – 当调用它时,我在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
        });
};

如果我检查响应,我看到状态200“OK”……我很困惑.

我究竟做错了什么?

解决方法

发生这种情况是因为发出AJAX请求的代码遵循重定向,而不是浏览器.这将失败,因为AJAX请求尝试访问其他域.如果要重定向浏览器,则应返回一些JSON结果或自定义HTTP标头,在jQuery中手动选择它,并在那里进行重定向.

在你的控制器中:

var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("FORCE_REDIRECT","http://google.com");

然后为AJAX调用添加成功回调:

success: function(data,textStatus,jqXHR) {
    if (jqXHR.getResponseHeader('FORCE_REDIRECT') !== null){
        window.location = jqXHR.getResponseHeader('FORCE_REDIRECT');
        return;
    }
}

在过去,我已将控制器结果包装在自定义操作结果类中以供重用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读