However in Sharepoint you may encounter with the problem when use this method. Check the line 9 in the code above which adds service reference to script manager.
Path contains the url to the service. As you can see it is located in layouts folder, i.e. it can be called in context of any Sharepoint site. Also we specified that generated proxy should be added as inline script to the output html (referenceProxy.InlineScript = true). In this case we need to use relative url in the ServiceReference.Path property as it is said in the documentation:
If the InlineScript property is set to true, then you must use a relative path that points to the same Web application as the page that contains the ServiceReference instance.
In our example path is relative, so it should be Ok. However if this code runs not on the root site, but on some sub site (e.g. http://example.com/subsite) we will have problem: relative path which we specified will be combined with root url, i.e. web service will be executed in context of root site, but not in context of the sub site. I.e. full url will be the following: http://example.com/_layouts/test/test.asmx. It may cause different problems, e.g. if locale of subsite differs from locale of the root site your users may see incorrectly localized content.
In order to fix it first of all we need to comment the line which sets InlineScript to true. It will allow us to use absolute url in the Path property:
These changes will have the following effect. Proxy will be added as external js file via <script> tag. Src attribute will contain absolute url:
(it added “/jsdebug” to the absolute url to the asmx). As you can see js proxy is loaded from context of the correct sub site now. So problem is solved? Unfortunately no. When you will check SPContext.Current.Web.Url property in the debugger of the web method, you will see that code still runs in context of the root site (it will contain http://example.com url, instead of http://example.com/subsite). And this is regardless of the site in which content js proxy was loaded.
In order to fix it we need to perform one extra step. Open the url which is specified in the src script. You will see the code of the proxy. It contain line which we are interesting in:
And it fixes the problem finally. Now the code of asmx web service will be executed in the context of the sub site. Hope that it will help you. E.g. you will encounter with this problem if will use framework for loading web parts asynchronously which I wrote above in the following post: Create asynchronous web parts for Sharepoint.
PS. However the described solution doesn’t fix problem with different locales which I used as example :) Some time ago I wrote how Sharepoint sets locale of the current thread using language of requested SPWeb: see this post. But because of some reason it didn’t happen in this case. So I fixed problem with locale manually:
After that current thread’s locale became correct.