我想将一个字符串传递给.ashx页面.
通常我会通过在.aspx页面中设置一个参数来做到这一点,例如: Loader="TreeLoader.ashx?passedVariable=hello"
但我想在.aspx.cs端以编程方式执行此操作,因为该值将更改.
.ashx页面接受HTTPContext:
public void ProcessRequest(HttpContext context)
{
Run Code Online (Sandbox Code Playgroud)
不应该有一些方法将参数添加到上下文,然后以类似于这样的方式获取参数:
string searchString = context.Request["searchString"];
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么?
正确的方法取决于控件如何从aspx文件传递给ashx.如果从服务器端调用处理程序(使用Server.Transfer方法),那么您可以使用上下文对象本身.例如,在aspx.c文件中
HttpContext.Current["key"] = data;
Server.Transfer("TreeLoader.ashx");
Run Code Online (Sandbox Code Playgroud)
并在ashx文件中
public void ProcessRequest(HttpContext context)
{
var data = context["key"];
...
Run Code Online (Sandbox Code Playgroud)
优点是您可以将实际对象作为数据传递(而不一定是字符串).
如果将从客户端(浏览器)端进行调用,则需要将数据作为查询字符串参数传递 - 例如TreeLoader.ashx?searchString=data并在ashx中使用它context.Request["searchString"].