【问题标题】:Redirect from asp.net web api post action从 asp.net web api 发布操作重定向
【发布时间】:2012-07-04 16:47:14
【问题描述】:

我对 ASP.NET 4.0 Web API 非常陌生。我们可以在 POST 操作结束时重定向到另一个 URL 吗?例如... Response.Redirect(url)

实际上,我通过 Web API(例如 www.abcwebapi.com/upload)从 MVC 应用程序(例如 www.abcmvc.com)上传文件

这里的upload 是POST 操作。我将多部分表单发布到 Web API 上传控制器的发布操作。上传后我想重定向回www.abcmvc.com

这可能吗?

【问题讨论】:

    标签: asp.net-mvc c#-4.0 asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    当然:

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

    【讨论】:

    • 使用此重定向技术解决了我使用其他重定向技术获得的“对象移动到”WebAPI 页面。同样对于临时重定向而不是永久重定向,您可以使用 HttpStatusCode.Redirect (302) 或 .RedirectMethod (303)
    • @Darin Dimitrov,这行得通。为什么当我改用 HttpStatusCode.Redirect 时,我的客户端会收到 401 响应?
    【解决方案2】:

    这是另一种无需对 url 进行硬编码即可到达网站根目录的方法:

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

    注意: 仅当您的 MVC 网站和 WebApi 在同一个 URL 上时才有效

    【讨论】:

      【解决方案3】:
          [HttpGet]
          public RedirectResult Get()
          {
              return RedirectPermanent("https://www.google.com");
          }
      

      【讨论】:

        【解决方案4】:

        你可以检查一下

        [Route("Report/MyReport")]
        public IHttpActionResult GetReport()
        {
        
           string url = "https://localhost:44305/Templates/ReportPage.html";
        
           System.Uri uri = new System.Uri(url);
        
           return Redirect(uri);
        }
        

        【讨论】:

        • @dotnetguy 请停止建议相同的编辑。如果需要,请将您更改的代码发布在单独的答案中。继续编辑没有意义,审稿人会拒绝每次编辑。
        猜你喜欢
        • 1970-01-01
        • 2018-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        相关资源
        最近更新 更多