Friday, June 12, 2015

Fix Operation is not valid due to the current state of an object when call ashx handler in Sharepoint context

Custom ashx handler may be useful in Sharepoint e.g. when we need to return some server data in json format in order to consume it on the client side. In this case we most probably copy ashx to subfolder of 14 or 15/Layouts folder and call it in context of Sharepoint site: http://example.com/_layouts/foo/bar.ashx. If in codebehind of ashx handler we need to reopen site under elevated privileges like shown below:

   1: SPSecurity.RunWithElevatedPrivileges(
   2:     () =>
   3:         {
   4:             using (var site = new SPSite(SPContext.Current.Site.ID,
   5:                 SPContext.Current.Site.Zone))
   6:             {
   7:                 using (var web = site.OpenWeb(SPContext.Current.Web.ID))
   8:                 {
   9:                     ...
  10:                 }
  11:             }
  12:         });

we may get exception:

Operation is not valid due to the current state of an object

In order to avoid it we need to use slightly different code:

   1: var currentSite = SPContext.Current.Site;
   2: var currentWeb = SPContext.Current.Web;
   3: SPSecurity.RunWithElevatedPrivileges(
   4:     () =>
   5:         {
   6:             using (var site = new SPSite(currentSite.ID, currentSite.Zone))
   7:             {
   8:                 using (var web = site.OpenWeb(currentWeb.ID))
   9:                 {
  10:                     ...
  11:                 }
  12:             }
  13:         });

Hope that it will help someone.

No comments:

Post a Comment