You need to enable JavaScript to run this app. ASP.NET Core MVC控制器中如何为重定向设置Content-Type
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC控制器中如何为重定向设置Content-Type

方案1:直接修改Response的ContentType后返回RedirectResult(更推荐)

RedirectResult本身已经自动处理了Location响应头和301状态码的设置,你只需要在返回前给当前Response的ContentType赋值即可:

Response.ContentType = "application/json";
return RedirectPermanent(url);

这种方案无需手动处理重定向的核心参数,出错概率更低。

方案2:使用ContentResult手动补充Location响应头

HTTP重定向的核心是响应头中的Location字段,你只要把跳转地址赋值到这个字段即可:

var contentResult = new ContentResult
{
    ContentType = "application/json",
    StatusCode = (int)HttpStatusCode.MovedPermanently,
    Headers = new HeaderDictionary { { "Location", url } }
};
return contentResult;

如果你使用的是旧版本框架,ContentResult不支持直接设置Headers,也可以直接操作当前Response的响应头:

Response.Headers.Add("Location", url);
var contentResult = new ContentResult
{
    ContentType = "application/json",
    StatusCode = (int)HttpStatusCode.MovedPermanently
};
return contentResult;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 01:06:04