【问题标题】:how to use response.redirect in webapi+asp.net?如何在 webapi+asp.net 中使用 response.redirect?
【发布时间】:2016-10-11 16:42:47
【问题描述】:

我想从WebAPI 重定向到另一个.aspx 页面。我已经使用了这段代码,但它不起作用:

string url = "http://localhost:61884/UserList.aspx";
System.Uri uri = new System.Uri(url);
return Redirect(uri).ToString();

【问题讨论】:

  • 您是否使用 Fiddler 或其他嗅探器测试过请求实际上并未重定向到目标文件?因为这可能是与服务器无关的客户端问题。
  • 您没有或您对问题的描述不准确。 Web API 旨在检索数据或持久化数据,基本上是一种从客户端与服务器交互的方式,而无需执行传统的表单发布或页面请求。一旦检索到调用 Web API 的结果,调用者需要执行重定向。 Web API 不应进行任何类型的重定向。

标签: angularjs asp.net-web-api asp.net-web-api2


【解决方案1】:

你没有。 (或者你对问题的描述不准确

Web API 旨在检索数据或保留数据,它是一种从客户端与服务器交互的方式,而无需执行传统的表单发布或页面请求调用。一旦检索到调用 Web API 的结果,调用者(基于您的问题标签 angularJs 的 JavaScript)需要执行重定向。

  • 这是很好的 SOC(关注点分离),Web API 中的业务逻辑不应该关心路由(angularjs)/网页。
  • 即使您想要 Web API,由于它的调用方式,也无法重定向客户端。

总结:Web API 代码本身不应该对客户端进行任何类型的重定向。客户应该处理这个。


对 web api 的示例调用并从角度代码重定向:

$http({
    url: "/api/SomeWebApiUrl",
    data: {},
    method: "POST",
    headers: { 'Content-Type': "application/json" },
    responseType: "json"
}).then(function (response) {
    if(response.data.somethingToCheck === someConditionThatWarrentsRedirect)
        $window.location.href = "~/someOtherUrl/";
});

【讨论】:

    【解决方案2】:

    试试这样的:

    var response = Request.CreateResponse(HttpStatusCode.Moved);
    string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
    response.Headers.Location = new Uri(fullyQualifiedUrl);
    

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      Redirect from asp.net web api post action

      public HttpResponseMessage Post()
      {
         // ... do the job
      
         // now redirect
         var response = Request.CreateResponse(HttpStatusCode.Moved);
         response.Headers.Location = new Uri("http://www.abcmvc.com");
         return response;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-09
        • 1970-01-01
        • 2013-06-24
        • 1970-01-01
        • 2021-12-30
        相关资源
        最近更新 更多