I'm trying to develop and event handler which reads PDF files in ItemAdding method.

After reading a bit on the internet, I finally found a way to do so.

When uploading a file through a browser, everything works as intended. But when use a script executing a raw HTTP PUT, it does not work anymore. I get a null HttpContext.Current in the event constructor.

My guess is that when doing an HTTP PUT, I'm not in an HttpContext but in something else, like an OperationContext or a WebOperationContext, like explained on StackOverflow.

But if I try to get a current OperationContext or WebOperationContext, it returns null.

Is there anything I should know here?


You definetely can't rely on the current HTTPContext, or even on SPContext.Current, since uploads can occur from direct OM calls (PowerShell, consol apps, ...). And in these cases, there's no context at all, only direct connections to the SQL DB from the process running the code (PowerShell, console app...).
I always have this simple rule of thumb: no HTTPContext.Current or SPContext.Current in event receivers. I've seen this error (that leads to immediate crashes) a lot in projects I audit. Don't assume upload is done from the Web context.

The only option I can see here is to read the content from a synchronous ItemAdded, remove the file if you don't like it, and raise an error after deleting it.

  • Ok, thanks for the fast answer. I totally understand that it's a bad idea to use HttpContext.Current. So let's say I want to raise an error after deleting the wrong file. I can't find a way to return an error code when doing so ? If i change properties.Status to an Error in ItemAdded, I still get a "200 OK" to the PUT request. Throwing an exception does not change the HTTP return code either. – Gaël G. Oct 19 '15 at 12:34
  • ItemAdded is executed asynchronous by Default. So the Item will be added and you get a OK. You don´t get direct Responses from asynchronous Events. Use ItemAdding instead (or, not recommenced, Change the execution of your itemAddedReceiver to synchronous manually). – Leopold Lerch Oct 19 '15 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.