Open an SPWeb from a single Url
When I want to get to a web, I usually have to do code like the following开发者_如何学编程 which is fairly self explanatory.
using (SPSite site = new SPSite(siteUrl))
{
SPWeb web = null;
if (string.IsNullOrEmpty(webName))
web = site.RootWeb;
else
web = site.AllWebs[webName];
...
web.Close();
}
Given a url that points directly to a web:
So in this case siteUrl would be: http://localhost/sites/testsite
and webName would be: testWeb
I would like to simply get a single bit of information from the user opposed to these two seperate bits, ie the url directly to the web: http://localhost/sites/testsite/testweb/
I would like to use this url to open the web and not have to specify the web name manually. I've played with site.OpenWeb and tried passing the url to this too but it doesn't like that. It only wants a server relative url. Is there a way to just be able to get a single url from the user in order to open the web, short of pulling the url apart and making assumptions that the last bit may or may not be the name of the web depending on whether we're going to the root web or not but then that makes the code even worse.
You don't need split the absolute SPWeb URL to access the SPWeb. You can simply do the following.
using (SPSite site = new SPSite(<url to spweb>))
{
using(SPWeb web = site.OpenWeb())
{
// put your code here ...
}
}
You can put the code as belows:
using (SPSite site = new SPSite(HttpContext.Current.Request.Url.ToString()))
{
using (SPWeb web = site.OpenWeb())
{
// TODO:.....
}
}
Agree with Flo, but there is a special detail you need to take attention.
If you use the SPSite contructor with no params, it means that you will create a instance with default url zone. There are 5 sharepoint url zone, such as: 1. Default, 2. Intranet, 3. Internet, 4. Custom, 5. Extranet.
A zone associates an incoming request URL with an outgoing URL. Any number of incoming request URLs can be specified per zone but only one outgoing URL can be specified per zone. There must always be an outgoing URL associated with the default zone.
- SPSite(Guid)
- SPSite(String)
- SPSite(Guid, SPUrlZone)
- SPSite(Guid, SPUserToken)
- SPSite(String, SPUserToken)
- SPSite(Guid, SPUrlZone, SPUserToken)
And you can also create the instance with a user token, and then the site instance is according to the user permission(as the user login in the site). In a word, the permission will be different with the SPSite different constructor, so you must be careful use it.
For more info pelease visit the following url:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.spsite.aspx
精彩评论