How to set Response Header before Server.Transfer in Asp.Net?

后端 未结 3 829
陌清茗
陌清茗 2021-01-13 13:41

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 fo

3条回答
  •  心在旅途
    2021-01-13 14:00

    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()
        {
        }
    }
    

    Cheers!

提交回复
热议问题