Skip to main content
 首页 » 编程设计

c#之响应 header 设置在 View 中消失之asp net mvc

2024年02月23日16yxwkf

在 Controller Action 中,响应头是这样设置的:

HttpContext.Response.AddHeader("key", "value"); 

在呈现的 View 中,Response.Headers["key"] 似乎为空(顺便说一句,在 ajax 请求中, header 的设置和检索没有任何问题)。这是否有任何特殊原因,或者这是我代码中的一个愚蠢错误?

请您参考如下方法:

您只能添加响应 header 但不能读取它们,除非您在 IIS 7 集成管道模式下运行。在标准模型中运行时,当您尝试在代码中读取它们时,HTTP 响应 header 将在稍后阶段发送。这已在 documentation 中说明:

The Headers property is only supported with the IIS 7.0 integrated pipeline mode and at least the .NET Framework 3.0. When you try to access the Headers property and either of these two conditions is not met, a PlatformNotSupportedException is thrown.

也就是说, View 应该访问的只是 View 模型,而不是响应 header 。因此,在您的 Controller 操作中,您将构建一个包含 View 所需的所有信息的 View 模型,并将其传递给 View 以供使用。请记住: View 不会拉取数据, View 使用以 View 模型的形式从 Controller 处理的数据。