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
相关产品推荐
相关产品推荐

