开发者

In Sharepoint using the Client Object Model, how can I determine if a URL represents a site

开发者 https://www.devze.com 2023-03-03 12:19 出处:网络
Using managed code, I believe I can do something like the following which can both tell me if the URL is valid, and, if so, if it represents a site.

Using managed code, I believe I can do something like the following which can both tell me if the URL is valid, and, if so, if it represents a site.

using (SPSite site = new SPSite(url))
{
    using (SPWeb web = site.OpenWeb())
    {
       if (url.TrimEnd('/').EndsWith(web.ServerRelativeUrl.TrimEnd('/'))
       {
           // The url represents a site
       }
    }
}

I've tried something similar using the Client Object Model.

Clien开发者_运维知识库tContext context = context = new ClientContext(url);
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();

As far as I can tell, this will throw an exception if the URL represents something other than a site, like a folder or a library. That's good as I can use the exception to determine if the URL represents a site. But I'd also like to be able to differentiate between a URL which is valid but doesn't represent a site, and a URL which is simply not valid.

Is this possible?


When you say "a URL which is simply not valid," do you mean a malformed URL, or a correctly-formed URL that doesn't resolve anywhere? I'm pretty sure you mean the former.

If you're just looking for well-formedness, I suggest attempting to parse it into a Uri object:

string testUrl = "http://stackoverflow.com/";
Uri goodUri;
if (Uri.TryCreate(testUrl, UriKind.Absolute, out goodUri)) {
    // testUrl == well-formed URI
}

I use the Uri class a lot, especially before I try to feed it into the SharePoint API for Sites and Webs. I tend to need to hack on it some, either to make a relative URL absolute for my current SP server, or to get parts of the path to resolve to relative locations from the current site.


Just for the sake of completeness, if you ever are trying to determine if a URL resolves somewhere or not, you can create an HTTP request and test it:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(goodUri);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
if (resp.StatusCode == HttpStatusCode.OK) {
    // Received 200 OK -- probably a valid URL
}
resp.Close();

Of course, the HTTP example above is incredibly, naively, simple. There could be all kinds of responses, or requirements for certain request properties to be set, etc. Review the documentation for HttpWebRequest and HttpWebResponse for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消