共用方式為


Getting References to Sites, Web Applications, and Other Key Objects

Applies to: SharePoint Foundation 2010

In order for your code to work with a deployment of Microsoft SharePoint Foundation, it must first get a reference to the objects that it must work with, including Web sites, site collections, and Web applications. There are two methods to do this: one method applies when your code will be used in a console or Windows-based application; the other applies when your code will be used in a browser-hosted application, such as when you choose "Web Site" as the type of Microsoft Visual Studio project.

Note

Most sample code in the Microsoft SharePoint 2010 Software Development Kit (SDK) is written for a browser-hosted application, so if you are writing for a console or Windows-based application, you must change the code. For guidance in doing this, see "Console and Windows Applications: Use Object Constructors" later in this topic.

Browser-Hosted Applications: Establish Site Context

To work with a deployment of SharePoint Foundation by means of a browser-hosted application, your code must first establish the site context or site collection context for requests that are made to the server.

You must obtain the HTTP context of the request in the code. Microsoft recommends that you do this by using the Microsoft.SharePoint.SPContext class and its members. Some examples are as follows.

To return the current site collection, you can use the Current.SPContext.Site property.

Note

All examples in this article require a using directive (Imports in Microsoft Visual Basic) for the Microsoft.SharePoint namespace.

Dim oSiteCollection As SPSite = SPContext.Current.Site
SPSite oSiteCollection = SPContext.Current.Site;

To return the Web site of the current request, you can use SPContext.Current.Web.

Dim oWebSite As SPWeb = SPContext.Current.Web
SPWeb oWebSite = SPContext.Current.Web;

Alternatively, when your code is contained in an .aspx file or the "code behind" in an .aspx.cs file, you can use methods of the SPControl object with the Page.Context property as the parameter. For example, use the GetContextWeb(HttpContext) method to get a reference to the current Web site.

Dim oWebSite As SPWeb = SPControl.GetContextWeb(Context)
SPWeb oWebSite = SPControl.GetContextWeb(Context);

Finally, if your .aspx page inherits from LayoutsPageBase instead of Page, you can use the Site or Web properties of the former class to obtain references to, respectively, the current site collection or Web site. (Or you can use the Microsoft.SharePoint.WebControls.LayoutsPageBase.Context property as the parameter to the GetContextWeb(HttpContext) and GetContextSite(HttpContext) methods.) LayoutsPageBase gives you some extra SharePoint-oriented functionality, mainly in connection with managing user rights to the page that is not available with Page.

For example, the following code, when used in an .aspx page that inherits from LayoutsPageBase (or the code behind the page) gets a reference to the current Web site.

Note

This example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint.WebControls namespace.

Dim oWebSite As SPWeb = this.Web
SPWeb oWebSite = this.Web;

Warning

You should not dispose any SPSite or SPWeb object obtained by any of the above methods. The SharePoint Foundation runtime will dispose of them after page completion. Calling the Dispose or Close method of these objects results in unpredictable behavior. This is in marked contrast to obtaining references to these types of objects by using a constructor, as described later in this topic in the section titled "Console and Windows Applications: Use Object Constructors". There are a number of nuances to the best practices with regard to when SharePoint Foundation objects should and should not be disposed. Carefully study Disposing Objects.

To return the current top-level server farm object, use SPContext.Current.Site.WebApplication.Farm.

Dim oFarm As SPFarm = SPContext.Current.Site.WebApplication.Farm
SPFarm myFarm = SPContext.Current.Site.WebApplication.Farm;

To return the top-level Web site of the current site collection, use the RootWeb property.

Dim oTopSite As SPWeb = SPContext.Current.Site.RootWeb
SPWeb oTopSite = SPContext.Current.Site.RootWeb;

The SPContext class does not limit you to getting the current object of any specified type. For example, you can use the SPSite.AllWebs property to obtain a reference to a Web site other than the current one. The following code returns the context of a specified site by using an indexer with the AllWebs property.

Warning

You should explicitly dispose of references to objects that are obtained through the AllWebs property. There are a number of nuances to the best practices with regard to when SharePoint Foundation objects should and should not be disposed. Carefully study Disposing Objects.

Dim oWebSite As SPWeb = 
    SPContext.Current.Site.AllWebs("myOtherSite")
...
oWebSite.Dispose();
SPWeb oWebSite = SPContext.Current.Site.AllWebs["myOtherSite"];
...
oWebSite.Dispose();

// Even better, take advantage of a "using" block to ensure
// that the object is disposed.
using (SPWeb oWebSite = SPContext.Current.Site.AllWebs["myOtherSite"])
{
...
}

Finally, to get a reference to either the server farm or the current physical server, you can use the static properties SPFarm.Local and SPServer.Local. The following line is an example.

Dim oFarm As SPFarm = SPFarm.Local
SPFarm oFarm = SPFarm.Local;

To use either of the Local properties, you must add using directive (Imports in Visual Basic) for the Microsoft.SharePoint.Administration namespace.

You can use any of the preceding techniques not only in Web applications and .aspx pages, but also in custom Web services and Web Parts.

Console and Windows Applications: Use Object Constructors

The SPContext class has no meaning in a console or Windows-based application. If you are writing code for either of those types of applications and you want to work with a specific site collection, use the SPSite constructor to instantiate an object that represents the site collection, as in the following example.

Note

Your code should dispose any SPSite or SPWeb object obtained by using a constructor. There are a number of nuances to the best practices with regard to when SharePoint Foundation objects should and should not be disposed. Carefully study Disposing Objects.

Dim oSiteCollection As New SPSite("https://localhost")
...
oSitecollection.Dispose();
SPSite oSiteCollection = new SPSite("https://localhost");
...
oSitecollection.Dispose();

// Even better, take advantage of a "using" block to ensure
// that the object is disposed.
using (SPSite oSiteCollection = new SPSite("https://localhost"))
{
...
}

Note

The "localhost" is a Windows alias for the computer on which the code is running. For console applications, Microsoft recommends that you always use "localhost" instead of the actual server name. The reason for this is because a console application can only operate on the local computer anyway. If you hard code a server name, such as "MyServer", then your console application cannot be ported to another computer and your console applications will break if the server's name is ever changed.

After you have a reference to a collection, you can use the AllWebs collection to obtain a reference to a particular web site in the collection.

Dim oWebSite As SPWeb
oWebSite = mySiteCollection.AllWebs("mySite")
...
oWebSite.Dispose();
SPWeb oWebSite = mySiteCollection.AllWebs["mySite"];
...
oWebSite.Dispose();

// Even better, take advantage of a "using" block to ensure
// that the object is disposed.
using (SPWeb oWebSite = mySiteCollection.AllWebs["mySite"])
{
...
}

Alternatively, you can use the OpenWeb method as shown in the following line.

Dim oWebSite As SPWeb
oWebSite = mySiteCollection.OpenWeb("mySite")
...
oWebSite.Dispose();
SPWeb oWebSite = mySiteCollection.OpenWeb("mySite");
...
oWebSite.Dispose();

// Even better, take advantage of a "using" block to ensure
// that the object is disposed.
using (SPWeb oWebSite = mySiteCollection.OpenWeb("mySite"))
{
...
}

If your code already has a reference to an SPSite or SPWeb, you can use it to get a reference to its parent objects. This technique is illustrated in the following lines, in which mySiteCollection is an SPSite object and oWebSite is an SPWeb object.

Dim parentSiteCollection As SPSite = oWebSite.Site;
Dim content As SPContentDatabase = mySiteCollection.CurrentDatabase;
Dim webApplication As SPWebApplication = mySiteCollection.WebApplication;
Dim farm As SPFarm = mySiteCollection.WebApplication.Farm;
SPSite parentSiteCollection = oWebSite.Site;
SPContentDatabase content = mySiteCollection.CurrentDatabase;
SPWebApplication webApplication = mySiteCollection.WebApplication;
SPFarm farm = mySiteCollection.WebApplication.Farm;

However, you should avoid constructing an SPSite or SPWeb object simply to get a reference to a parent object. These objects occupy a large amount of memory. Instead, to get a reference to a Web application, use the static Lookup(Uri) method and pass it a SystemUri object that is created with the URI of the Web application. You can then get a reference to the farm by using the Farm property of the Web application object. (You can get a reference to a remote farm by using the static Open(String) method.) The ContentDatabases property of the Web application object contains a collection of the content databases in the Web application. You can get a reference to a particular content database through this property if you know its index in the collection. For more information, see the reference topic for the SPContentDatabaseCollection class. The following lines illustrate some of these points.

SPWebApplication webApplication = Lookup(new Uri("https://localhost/");
SPFarm farm = webApplication.Farm;
SPContentDatabase content = webApplication.ContentDatabases[0];

See Also

Reference

Determining Where to Build a Custom Application

Concepts

Disposing Objects

SharePoint Development Tasks - How Do I...?

Other Resources

Basic Object Model Tasks in SharePoint 2010