¿Cuál es la diferencia entre spcontext.current.web.url y spcontext.current.site cuando se usa un objeto SPSITE?

sharepoint.stackexchange https://sharepoint.stackexchange.com//questions/95812

  •  10-12-2019
  •  | 
  •  

Pregunta

SPSite spsite1=new SPSite(SPContext.Current.Web.URL);

SPSite spsite2=SPContext.Current.Site;

¿Cuál es la diferencia y cuándo decidimos cuál usar?

Me siento que tanto nos dan el objeto de colección del sitio.

Ejemplo: SPWeb spweb=spsite1.RootWeb; significará igual que spsite2.RootWeb;, ¿por qué hay 2 formas de hacerlo?

¿Fue útil?

Solución

SPSite spsite1=new SPSite(SPContext.Current.Web.Url); will give you SPSite object. But it will be site collection object only when SPContext.Current.Web.Url is that of root web. If the web object is that of a sub site then SPSite object won't be a site collection object. The second statement SPSite spsite2=new SPSite(SPContext.Current.Site); is wrong because there is no overload of SPSite which has SPSite as parameter.

UPDATE

If the intention is to get the rootweb then second is a better way of doing it as you are not instantiating a new SPSite object. Moreover, in the first case you will need to dispose SPSite object as you are creating a new one compared to second in which SPSite is retrieved through SPContext which should not be disposed explicitly.

Otros consejos

The both site1 and site2 returns the same site collection (SPSite) object. By calling RootWeb property on both objects, We can get the same top-level web site (SPWeb) object.

Instruction1: SPSite spsite1=new SPSite(SPContext.Current.Web.URL);

Process: If we are in subsite and we are calling the above code, first it get the current subsite web url and pass it to SPSite constructor to get the current Site Collection object.

Instruction2: SPSite spsite2 = SPContext.Current.Site;

Process: Now we are in subsite and we are calling the above code, which directly retrives the Site Collection object. There is no looking for web url parameter to get the SiteCollection.

Result:

spsite1.RootWeb and spsite2.RootWeb returns the same Top-Level web SPWeb object.

spsite1.OpenWeb() returns the subsite (SPWeb) object if we are in subsite. spsite2.OpenWeb() returns the top-level site (SPWeb) object, even we are in subsite.

For the spsite1, we have to call dispose method to dispose the SPSite object. But for the spsite2, the sharepoint will take care on disposing of SPSite object.

Licenciado bajo: CC-BY-SA con atribución
scroll top