Get application root from Request object that works locally and remotely - asp.net

Let's say that I have my ASP.NET web application in a directory called "MyApp" both locally and on a remote server. I'm trying to build an onclick response to a link. The response calls a Javascript function, passing it the URL of an .aspx page in my web app. The Javascript pops out a new window displaying the page. My C# code looks like this:
link = new HyperLink();
link.Text = product_num_str;
link.NavigateUrl = "#";
string url = "Javascript:My_NewWindow('http://" +
HttpContext.Current.Request.Url.Authority +
"/ProductInfo.aspx?_num=" + product_num_str + "')";
link.Attributes.Add("onclick", url);
I started using the Request's Authority property because I was having problems running locally on the Visual Studio web server when I used the Host property. The problem was that Host only returned "localhost" instead of the host and port number.
When tested locally, the code works because the "authority" maps to my app root folder. The URL generated is, e.g.,
http://localhost:52071/ProductInfo.aspx?_num=123
If I run on a remote server, however, I end up with something like:
http://company-server/ProductInfo.aspx?_num=123
This fails to find the page, because in this case the "MyApp" root folder must be included.
There is probably an easier way - putting an entry in the web.config or something. My motivation originally was to allow the app to be published to a folder of any name and work as is.
I could hack my approach and search the string for "localhost" or something, but that's ugly. So how do I build a string that will work everywhere?

I'm assuming you're doing this from within a Page or Control. If that's the case you should do this instead:
string fullUrl = this.ResolveClientUrl("~/ProductInfo.aspx?_num=" + product_num_str + ");
That will give you the proper URL no matter where the application is deployed.

Related

Unable to use WebService specifing the URI through code

I have two PCs conected with a LAN. Firewall ports are opened.
I'm running a WebService on A machine, using IIS. Of course, I can access the WebService (on A) through the Web Browser on the B machine, so I'm sure the WebService can be accessed remotely.
Now, I'm running a console app on B machine, developed in vb.net, which will access the WebService of A machine.
Both, the console app and the WebService, has been developed on VS2010.
Creating the reference on the project, I can see and use the WebService. But I need to specify on code the URI due to the WebService may change its location.
The code indicating the URI manually:
Dim myService As New MiServicioWeb.WebServiceSoapClient("192.168.1.13:8080")
This line throw an exception with the message that did not find any element with the name indicated. I have tried too, without success, the following lines:
This one:
Dim myService As New MiServicioWeb.WebServiceSoapClient("192.168.1.13")
And this one:
Dim myService As New MiServicioWeb.WebServiceSoapClient("192.168.1.13:8080/ServicioWeb.asmx")
But the result is always the same.
Some user (raja) wrote an answer a few days ago indicating that this should work, but I don't know the reason why does not work in my case.
As I said before, if I create the reference on the project, and I use the following line of code:
Dim myService As New MiServicioWeb.WebServiceSoapClient()
It works!, but what I need is to set the URI manually...
Some help will be thankful.
if not already present, you need to modify the proxy class to have a constructor that can take a Uri and set it. This Uri needs to be supplied to the proxy.
Dim uriFromConfig as String;
// read uriFromConfig from config or set it accordingly.
Dim myService As New MiServicioWeb.ServicioWebSoapClient(uriFromConfig);
this way, any ASMX can be called, as long as the right Uri is provided.
in summary to call a webservice hosted on machine with IP a.b.c.d from another machine:
Give the Proxy Uri with the IP Address. a.b.c.d
Open the port (50594) you're using in the machine hosting the web service from the Firewall settings.
Verify if the asmx is accesible by typing http://a.b.c.d:50594/ServicioWeb.asmx from the browser of the client machine. (not the machine hosting the web service)
if #3 is successful, then you'll see a nice page on the browser.
your client app should also be able to connect now.

how to change the url of web service from localhost to www(word wide web)

i have very simple problem , but the solution are very vast and complex ..
i have one asp.net web service . it is when i run it , url is like this :
http://:56197/Salesforce/SforceService.asmx?wsdl
i want to change it to like this :
http://www.site.com/Salesforce/SforceService.asmx?wsdl
what is mean to say just want to make web service globally and consume web service on remote in cross platform(salesforce)that URL dont to include and pc name of ip name
following suggestion i have tried :
create a wsdl file and export in wsdl format ... but it also include end point address in this format
/Salesforce/SforceService.asmx"/>
again local computer problem , how to modify soap url to access globally
create a proxy class using wsdl tool --> it generate .cs class , if this is right way then how to consume it on client side salesforce
i followed these links :
http://www.justskins.com/forums/dynamically-change-url-in-61352.html
(equivalent done in c#)
Dim rswb as new Testing.Service1()
rswb.URL = "http://Testing/Group/Service1.asmx"
But on service.cs class it doesnot show url proeprty
I am bit of confused and stuck
Please provide me any relative link ..
Thanks
Did you do a web reference or a service reference? I'm thinking you added a service refrence. You might want to change it to a web reference
When you add a reference there is an advanced button. Make sure you select add web reference.
I do this all the time adding a testing web service on my local development machine and switch it to the production one in code.
Dim myWS As New myWS.Update
'//create a new instance of the webservice object
Dim tmpURL as string = "ipaddress/domain name of actual host here"
myWS.Url = "http://" & tmpURL & ".asmx"

Get domain whatever local or webserver

I wrote an ASP.NET web application. My application created a request with returning URL other e-commerce server. I want to get this.
http://www.stackoverflow.com/question/ask --> http://www.stackoverflow.com
http://localhost/stackoverflow/question/ask --> http://localhost/stackoverflow
I used Request.Url.AbsoluteUri. But it's not OK for typing address by user.
How can this be done?
Look at the server variables collection. That is the source of this raw data that the HttpApplication gets from IIS.
I think the specific string you are looking for can be found with by "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"]
EDIT
Looking at your question again, this won't work for the "http://localhost/stackoverflow". This is because it doesn't follow the same convention. If you are using the convention that the public site is http://www.domainname.com/ and your development site is http://localhost/domainname, then you could write a function that gets the site name like
public static string GetDomainUrl(){
var servername = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
bool isLocalHost = serverName.ToLowerInvariant().Contains("localhost);
if(isLocalHost){
var domain = serverName.Split(new Char[]{'/'})[1];
return string.Format(#"http://localhost/{0}", domain);
}
return string.Format(#"http://{0}", serverName);
}
Note: I wrote this in the SO textbox, so check it.

MOSS 2007 404 error when accessing Lists.asmx webservice

Currently I have an ASP.net 4.0 app in which I've made a web reference to an MOSS 2007 server. When I access any lists.asmx methods from the root application, everything works fine. However, if I try to change the service URL in C# code-behind to that of a subfolders list.asmx, then access the any method, I get a 404 error. The really strange thing though is if I take the URL that I've changed it to and plug it manually into IE and run it, the service loads fine (giving me a list of any methods available as expected.)
Here's a rundown of my code that I'm using:
This works:
ListsService.Lists m_listService =
ICredentials m_credentials = CredentialCache.DefaultCredentials;
m_listService.Credentials = m_credentials;
// No change to URL, defaults to 'http://mosstest/SiteDirectory/RootApp/SubApp/_vti_bin/lists.asmx'
XmlNode listColl = m_listService.GetListCollection(); // Works fine, gives me collection of lists in the root folder.
This doesn't work:
ListsService.Lists m_listService =
ICredentials m_credentials = CredentialCache.DefaultCredentials;
m_listService.Credentials = m_credentials;
m_listService.Url = "http://mosstest/SiteDirectory/RootApp/SubApp/Subfolder1/_vti_bin/lists.asmx";
XmlNode listColl = m_listService.GetListCollection(); // Throws a 404 Not found error.
Anyone else run into something similar?
Turns out I was trying to access a List itself, which in turn was not an application. I'm learning this headfirst. I will note however that SP seems to not give a 404 error when accessing via the browser, regardless of the URL. If I type in something like "http://mosstest/SiteDirectory/RootApp/SubApp/Subfolder1/_vti_bin/lists.asmx", with SubFolder1 not existing, it still gives a list of methods "available" and runs as if a service was indeed there. Not sure why it does this, but it does cause a great deal of confusion.

How do I get the host domain name in ASP .NET without using HttpContext.Current.Request?

I've got an ASP .Net application running on IIS7. I'm using the current url that the site is running under to set some static properties on a class in my application. To do this, I'm getting the domain name using this (insde the class's static constructor):
var host = HttpContext.Current.Request.Url.Host;
And it works fine on my dev machine (windows XP / Cassini). However, when I deploy to IIS7, I get an exception: "Request is not available in this context".
I'm guessing this is because I'm using this code in the static constructor of an object, which is getting executed in IIS before any requests come in; and Cassini doesn't trigger the static constructor until a request happens. Now, I didn't originally like the idea of pulling the domain name from the Request for this very reason, but it was the only place I found it =)
So, does anyone know of another place that I can get the host domain name? I'm assuming that ASP .Net has got to be aware of it at some level independent of HttpRequests, I just don't know how to access it.
The reason that the domain is in the request is...that's what's being asked for. For example these are a few stackexchange sites from http://www.stackexchangesites.com/:
http://community.ecoanswers.com
http://www.appqanda.com
http://www.irosetta.com/
If you ping them, you'll see they all point to the same IP/Web Server and be served by the same app (or multiple apps in this case, but the example holds if it was one big one)...but the application doesn't know which one until a host header comes in with the request asking the server for that site. Each request may be to a different domain...so the application doesn't know it.
If however it doesn't change, you could store it as an appSetting in the web.config.
Use global.asax or write a HttpModule and subscribe to start request events. You will have the request passed into your event handler.
Use this instead:
HttpRuntime.AppDomainAppVirtualPath
Or if you want the physical path:
HttpRuntime.AppDomainAppPath
For further reading:
http://weblogs.asp.net/reganschroder/archive/2008/07/25/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-application-start.aspx

Resources