You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 3 WebAPI如何返回/重定向至网页(以CNN.com为例)

.NET Core 3+ 实现Web API重定向到外部网页的解决方案

嘿,这个问题我之前迁移项目的时候也踩过坑!在.NET Core 3及以后的版本里,原来ASP.NET Web API里的Request.CreateResponse方法确实被移除了,不过官方提供了更简洁、更符合.NET Core架构的替代方案,下面给你两种可行的实现方式:

方案一:使用ControllerBase内置重定向方法(推荐)

在.NET Core的Web API控制器中,你的控制器应该继承自ControllerBase,它提供了直接的重定向方法,代码写起来更简洁,也符合框架的设计思路:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class YourController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        try
        {
            // 临时重定向(对应HttpStatusCode.Redirect,状态码302)
            return Redirect("https://cnn.com");
            
            // 如果需要永久重定向(对应HttpStatusCode.MovedPermanently,状态码301),替换为:
            // return RedirectPermanent("https://cnn.com");
        }
        catch (Exception e)
        {
            ErrorSignal.FromCurrentContext().Raise(e);
            // 返回500错误及异常信息
            return StatusCode(StatusCodes.Status500InternalServerError, e);
        }
    }
}

注意:一定要写完整的URL(包含https://或http://),否则框架会把它当成相对路径处理,导致重定向失败。

方案二:手动构建HttpResponseMessage(兼容旧写法)

如果你希望尽量保持原来的代码结构,也可以手动构建HttpResponseMessage,不过需要注意兼容性:

首先,确保你的项目安装了Microsoft.AspNetCore.Mvc.WebApiCompatShimNuGet包(这个包是为了兼容旧Web API的一些特性),然后代码可以这样写:

using System.Net;
using System.Net.Http;
using System.Text.Json;

[HttpGet]
public HttpResponseMessage Get()
{
    try
    {
        var response = new HttpResponseMessage(HttpStatusCode.Redirect);
        response.Headers.Location = new Uri("https://cnn.com");
        return response;
    }
    catch (Exception e)
    {
        ErrorSignal.FromCurrentContext().Raise(e);
        var errorResponse = new HttpResponseMessage(HttpStatusCode.InternalServerError);
        // 将异常序列化为JSON返回
        errorResponse.Content = new StringContent(JsonSerializer.Serialize(e), System.Text.Encoding.UTF8, "application/json");
        return errorResponse;
    }
}

不过这个方案不如第一种简洁,而且需要额外安装兼容包,所以更推荐方案一。

简单总结下:.NET Core把Web API和MVC的返回体系统一成了IActionResult,所以用ControllerBase的内置方法是最符合当前框架设计的做法~

内容的提问来源于stack exchange,提问作者Jon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:52:42