如何将一些自定义数据与当前的HttpRequest相关联?

时间:2021-09-13 18:39:40

I need to somehow attach my custom data to the HttpRequest being handled by my IIS custom modules - so that code that runs in earlier stages of IIS pipeline attaches an object and code that runs in later stages can retrieve the object and use it and no other functionality of IIS pipeline processing is altered by adding that object.

我需要以某种方式将我的自定义数据附加到由我的IIS自定义模块处理的HttpRequest - 以便在IIS管道的早期阶段运行的代码附加一个对象,并且在后续阶段运行的代码可以检索对象并使用它而不是其他通过添加该对象来更改IIS管道处理的功能。

The data needs to persist within one HTTP request only - I don't need it to be stored between requests. I need it to be "reset" for each new request automatically - so that when a new request comes it doesn't contain objects my code attached to the previous request.

数据只需要在一个HTTP请求中保留 - 我不需要将它存储在请求之间。我需要它自动为每个新请求“重置” - 这样当一个新请求到来时它不包含我的代码附加到前一个请求的对象。

Looks like HttpContext.Items is the way to go, although MSDN description of its purpose is not very clear.

看起来像是HttpContext.Items的方法,虽然MSDN描述其目的不是很清楚。

Is using HttpContext.Current.Items the way to solve my problem?

是用HttpContext.Current.Items解决我的问题的方法吗?

1 个解决方案

#1


4  

This should work - I have done this in a project before.

这应该工作 - 我之前在一个项目中完成了这个。

I have a class which has a static property like this -

我有一个类有这样的静态属性 -

public class AppManager
{
    public static RequestObject RequestObject
    {
        get
        {
            if (HttpContext.Current.Items["RequestObject"] == null)
            {
                HttpContext.Current.Items["RequestObject"] = new RequestObject();
            }

            return (RequestObject)HttpContext.Current.Items["RequestObject"];
        }
        set { HttpContext.Current.Items["RequestObject"] = value; }
    }
}

And then RequestObject contains all my custom data so then in my app I can do

然后RequestObject包含我所有的自定义数据,然后在我的应用程序中我可以做

AppManager.RequestObject.CustomProperty

So far I have not come across any issues in the way HttpContext.Items works.

到目前为止,我还没有遇到HttpContext.Items工作方式的任何问题。

#1


4  

This should work - I have done this in a project before.

这应该工作 - 我之前在一个项目中完成了这个。

I have a class which has a static property like this -

我有一个类有这样的静态属性 -

public class AppManager
{
    public static RequestObject RequestObject
    {
        get
        {
            if (HttpContext.Current.Items["RequestObject"] == null)
            {
                HttpContext.Current.Items["RequestObject"] = new RequestObject();
            }

            return (RequestObject)HttpContext.Current.Items["RequestObject"];
        }
        set { HttpContext.Current.Items["RequestObject"] = value; }
    }
}

And then RequestObject contains all my custom data so then in my app I can do

然后RequestObject包含我所有的自定义数据,然后在我的应用程序中我可以做

AppManager.RequestObject.CustomProperty

So far I have not come across any issues in the way HttpContext.Items works.

到目前为止,我还没有遇到HttpContext.Items工作方式的任何问题。