开发者

How to obtain the HttpContext in Event Handler

开发者 https://www.devze.com 2022-12-09 15:42 出处:网络
I’m trying to obtain the HTTPContext within an Event Handler in a Document Library in MOSS, but all I have is a null value of the HTTPContext.Current, I do the same thing on a List and the HTTPContex

I’m trying to obtain the HTTPContext within an Event Handler in a Document Library in MOSS, but all I have is a null value of the HTTPContext.Current, I do the same thing on a List and the HTTPContext is returned. There is a way to obtain the HTTPContext in Document Libraries to access the HTTPContext.Request method?

Thanks for your help

Here is the code:

public class TestContextListItemEventReceiver : SPItemEventReceiver
{
    HttpContext current;
    static ob开发者_JS百科ject obj;

    /// <summary>
    /// Initializes a new instance of the Microsoft.SharePoint.SPItemEventReceiver class.
    /// </summary>
    public TestContextListItemEventReceiver()
    {
        current = HttpContext.Current;
    }

    public override void ItemAdding(SPItemEventProperties properties)
    {
        obj = current;  
    }
}


Step 1 Declare:

    private HttpContext currentContext;
    static HttpContext _stCurrentContext;

Step 2

currentContext = HttpContext.Current;      // in constructor

Step3

public override void ItemAdding(SPItemEventProperties properties)
                 _stCurrentContext = currentContext;

Step 4

 public override void ItemAdded(SPItemEventProperties properties)
 if (_stCurrentContext.Request.Files[0].ContentLength > 0)
 HttpPostedFile uploadfile = _stCurrentContext.Request.Files[0];


I faced the same issue when I was trying to update some custom fields of my document library when uploading new documents, the field was (ProjectID) which I put it inside a session in my webpart (the step before uploading the document).

What I did is: I put the projectID into the cache (per user) inside the custom webpart which acts as a session as follows:

if (Request.QueryString["ProjectID"] != null)
{
     HttpRuntime.Cache.Remove(SPContext.Current.Web.CurrentUser.LoginName);
     HttpRuntime.Cache.Add(SPContext.Current.Web.CurrentUser.LoginName,
                           ProjectID, null, DateTime.UtcNow.AddMinutes(60),
                           System.Web.Caching.Cache.NoSlidingExpiration,
                           System.Web.Caching.CacheItemPriority.Normal, null);
}

Then I implemented the ItemAdded event and I get the value of the cached projectId through:

public override void ItemAdded(SPItemEventProperties properties)
{
    try
    {
        string ProjID = "";

        string CreatedBy = null;
        if (properties.ListItem["Created By"] != null)
            CreatedBy = properties.ListItem["Created By"].ToString().Split(';')[1].Replace("#","");

        if (HttpRuntime.Cache[CreatedBy] != null)
        {  
            //SPContext.Current.Web.CurrentUser.LoginName;
            ProjID = HttpRuntime.Cache[CreatedBy].ToString();

            if (properties.ListItem["Project"] == null)
            {
                properties.ListItem["Project"] = new SPFieldLookupValue(ProjID);
                properties.ListItem.SystemUpdate();
            }

            base.ItemAdded(properties);
        }
    }
    catch (Exception ex)
    { }
}


An item event receiver run asynchronously; you will not have access to the HTTP request that initiated the event.


You can catch the HttpContext in both SPList and Document Libraries, if you upload the document from the SharePoint Interface (Internet Explorer). But if you save the document from Microsoft Word the HttpContext can't be catched, i don't know why.


Try using the HttpRuntime class


I can get the session object from inside ItemAdding Event if the user try to upload one document, but the problem is the httpcontext.current is always null when the user upload multiple documents using the document libarary option ( upload multiple document )


You can fake the HttpContext and SPContext in event receivers as described in my post: http://pholpar.wordpress.com/2011/06/26/injecting-httpcontext-and-spcontext-into-the-event-receiver-context/


If you place it in a static variable like that, you also have multiple people using the same context object that will be the context of the user who first ran the event receiver, and concurrent changes could have unexpected results.

The context is removed by design to encourage people not to use it. You should try to use the properties that are exposed as much as possible to avoid compatibility issues later. You can get the username off the properties.Web.CurrentUser as one example.

Using static variables in the event receiver is tricky, and you have to remember if you have multiple front ends, the data in the static variable is not available outside the frontend that the instance of the event receiver runs on.

0

精彩评论

暂无评论...
验证码 换一张
取 消