1

I have a SharePoint application that uses a URL to access a resource.

code:

return web.GetList(web.ServerRelativeUrl + "/lists/UserSettings"); 

This works fine when I'm on a subsite, because ServerRelativeUrl will return "/sitename"

However, when this is a root site, ServerRelativeUrl will return "/" instead, leading to a poorly formed URL such as "//lists/UserSettings"

I know this seems like a simple problem (and it is) but is there a best practice for approaching this situation that is consistently safe?

4 Answers 4

1

Have you seen the System.Uri and System.UriBuilder classes?

Sign up to request clarification or add additional context in comments.

1 Comment

Either way I get an exception of : "Invalid URI: The hostname could not be parsed."
1
new Uri(web.ServerRelativeUrl, "/lists/UserSettings"); 

Okay, hrm...try:

Path.Combine(web.ServerRelativeUrl, "/lists/UserSettings"); 

3 Comments

This doesn't work, because web.ServerRelativeUrl is (not intuitively) a string. Trying to put the full string in gives me an exception of "Invalid URI: The hostname could not be parsed."
What does the string version look like?
If the site is a root-site, it simply returns "/", which forms something like: "//lists/UserSettings", which is the invalid URI
1

Use absolute url, this works for me: web.GetList(web.Url + "/lists/UserSettings")

Comments

1
return web.GetList( (web.ServerRelativeUrl == "/" ? string.Empty : web.ServerRelativeUrl) + "/lists/UserSettings"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.