如何在C#中添加和访问自定义页眉 [英] How to add and access Custom Header in C#
问题描述
我需要添加一个自定义标题,如
MYName:Balaji
我需要通过
从.aspx文件访问Request.ServerVariables [HTTP_MYName];
应该返回Balaji。我需要很多像这样的变量,它会动态添加。
请帮助。
另外,我不能在任何.Net控件或对象(如
cookies,会话,应用程序,隐藏)中持久保存这些变量变量等,或不能将其存储在d / b中并在需要时将其取回,我只需要在HTTP头文件中。
请发送C#代码如何添加此变量并将值返回到.aspx文件中。
你的意思是将值存回.aspx文件? HTTP头旨在用作浏览器的指令,以及如何解释给定的内容。您无权访问您文档中的这些值。
然而,设置自定义HTTP标头非常简单:
Page.Response.AddHeader(MyCustomHeader,VerySecretValue)
根据您的评论更新我的回答。
如果您需要在HTTPModule和ASPX页面之间传输信息,可以使用 HTTPContext.Current
,因为这两个地方保持不变。
因此,您可以通过
HttpContext.Current.Items.Add(SecretKey,SecretValue)添加它;
并将其解读为
string s = HttpContext.Current.Items [SecretKey];
I need to add a custom header something like MYName: Balaji which i need to access from .aspx file through Request.ServerVariables["HTTP_MYName"]; should return "Balaji". I need so many variables like this it will added dynamically. Kindly help.
Also, I cannot persist this varaibles in any of the .Net controls or objects like cookies, sessions, application, hidden variable etc., or cannot store this in d/b and get it back whenever is required, I NEED IT ONLY IN HTTP HEADERS.
Kindly send the C# code how to add this variable and get the value back in .aspx file.
What do you mean by "get the value back in .aspx file"? HTTP headers are intended to be used as directives to a browser, how to interpret the given content. You don't have access to these values in your document.
Setting a custom HTTP header is quite easy, however:
Page.Response.AddHeader("MyCustomHeader", "VerySecretValue")
Updated my answer as per your comment.
If you need to transfer information between a HTTPModule and an ASPX page, you can use HTTPContext.Current
, since this stays the same in both places.
So, you add it by
HttpContext.Current.Items.Add("SecretKey", "SecretValue");
and read it as
string s = HttpContext.Current.Items["SecretKey"];
这篇关于如何在C#中添加和访问自定义页眉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!