如何Server.Transfer的之前设置响应头在Asp.Net? [英] How to set Response Header before Server.Transfer in Asp.Net?

查看:130
本文介绍了如何Server.Transfer的之前设置响应头在Asp.Net?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里根据一定的条件下,我无论做的Response.Redirect或Server.Transfer的页面。现在,我想添加一个标题为两种情况。所以,我做以下

I have a page where based on certain conditions I am either doing a Response.Redirect or Server.Transfer. Now I want to add a header for both the cases. So I am doing the following

    Response.AddHeader("Vary", "User-Agent");

    if (condition) 
    {
        Server.Transfer(redirectUrl);
    }
    else
    {
        Response.Redirect(redirectUrl);
    }

现在,当code通过Server.Transfer的code路径得好,Vary标头设置为*而当它通过Response.Redirect的去头正确设置为用户代理。

Now, when the code goes via Server.Transfer code path, the Vary header is set to * whereas when it goes via Response.Redirect the header is correctly set to User-Agent.

为什么会出现这种情况,我怎么可以设置响应头是相同的两个案例?

Why does this happen and how can I set the Response Header to be same for both the cases?

推荐答案

安德烈是正确的响应对象被替换为 Server.Transfer的的一部分。如果你想使你转移到无关的父的页面,您可以大概捶信息化为 HttpContext.Items ,然后使用 IHttpModule的来提取信息并适当配置的标题。像这样的东西可能会做的工作......

Andre is right that the Response object is replaced as part of Server.Transfer. If you want to make the page you're transferring to agnostic of the parent you can probably whack the information into HttpContext.Items and then use an IHttpModule to extract the information and configure the header appropriately. Something like this would probably do the job...

Items.Add(VaryHttpModule.Key, "User-Agent");

if (condition) 
{
    Server.Transfer(redirectUrl);
}
else
{
    Response.Redirect(redirectUrl);
}

public class VaryHttpModule : IHttpModule
{
    public const string Key = "Vary";

    public void Init(HttpApplication context)
    {
        context.PostRequestHandlerExecute +=
            (sender, args) =>
                {
                    HttpContext httpContext = ((HttpApplication)sender).Context;
                    IDictionary items = httpContext.Items;
                    if (!items.Contains(Key))
                    {
                        return;
                    }

                    object vary = items[Key];
                    if (vary == null)
                    {
                        return;
                    }

                    httpContext.Response.Headers.Add("Vary", vary.ToString());
                };
    }

    public void Dispose()
    {
    }
}

干杯!

这篇关于如何Server.Transfer的之前设置响应头在Asp.Net?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆