[英]In Sharepoint using the Client Object Model, how can I determine if a URL 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. 相信使用托管代码,我可以做类似以下的事情,既可以告诉我URL是否有效,如果可以,还可以代表一个站点。
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. 我已经尝试使用客户端对象模型进行类似的操作。
ClientContext 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. 据我所知,如果URL代表网站以外的其他内容(例如文件夹或库),则将引发异常。 That's good as I can use the exception to determine if the URL represents a site.
很好,因为我可以使用异常来确定URL是否代表网站。 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.
但是我也希望能够区分一个有效但不代表站点的URL和一个无效的URL。
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? 当您说“一个根本无效的URL”时,是指格式错误的URL还是格式正确的URL,该URL无法在任何地方解析? 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: 如果您只是在寻找格式良好的文件,建议尝试将其解析为
Uri
对象:
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. 我经常使用
Uri
类,尤其是在尝试将其馈入网站和网站的SharePoint API之前。 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. 我倾向于需要对其进行修改,以使当前SP服务器的相对URL绝对正确,或者获取部分路径以从当前站点解析为相对位置。
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: 只是为了完整起见,如果你正试图确定某个网址的地方或不结算时,你可以创建一个HTTP请求,并对其进行测试:
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. 当然,上面的HTTP示例天真地简单。 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.
可能有各种响应,也可能需要设置某些请求属性,等等。有关更多信息,请查阅HttpWebRequest和HttpWebResponse的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.