【问题标题】:ASP.NET Web API: How to do a Post back results with redirectionASP.NET Web API:如何使用重定向回发结果
【发布时间】:2025-12-29 20:50:15
【问题描述】:

我有一个 Web API,它执行一个函数并将 JSON 响应发布回调用页面。

这是标准的 Web API 行为,运行良好。

现在我想修改控制器,以便除了回发之外,用户还被重定向回调用网站上可以显示 Web API 调用结果的页面(以 JSON 格式)。

所以基本上我想: (1) 服务器端将结果以 JSON 格式回传到一个页面,并从 Web API 重定向到同一页面 (2) 在调用者的站点上,我想显示回传的 JSON。

我该怎么做?

我已经尝试了好几个小时... 例如:

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Content-Type", "text/json");
                client.Headers.Add("Accept", "text/json");
                try
                {
                    ErrorText = client.UploadString(redirectURL, "POST", JsonConvert.SerializeObject(orderresponse));
                    Response.Redirect(redirectURL);
                }
                catch (WebException err)
                {
                    ErrorText = err.Message;  //Todo - write to logfile
                }

            }

【问题讨论】:

    标签: json redirect postback asp.net-web-api


    【解决方案1】:

    不要在服务器上执行重定向,而是通过使用适当的 HTTP 状态代码来指示客户端执行此操作。例如:

    public HttpResponseMessage Post(MyModel model)
    {
        // handle the post
        MyResult result = ...;
    
        // redirect
        var response = Request.CreateResponse<MyResult>(HttpStatusCode.Moved, result);
        response.Headers.Location = new Uri("http://www.yourdomain.com/redirectURI");
        return response;
    }
    

    【讨论】:

      最近更新 更多