user455423
user455423

Reputation: 119

How can i get the requested url in a webservice using asp.net?

I am writing a WebService and wants to find out the URL the client used to call my WebMethod.

Ok..i will explain it in detail..

Suppose i have a webservice (http://myWebservice/HashGenerator/HashValidator.asmx) as follows

[WebMethod]
public string ValidateCode(string sCode)
{
  //need to check requested url here.The call will be coming from different sites
  //For example www.abc.com/accesscode.aspx
}

please send me a solution for this.

Upvotes: 10

Views: 48353

Answers (5)

BioFrank
BioFrank

Reputation: 195

You need this:

[WebMethod]
public static string mywebmethod()
{
string parameters =  HttpContext.Current.Request.UrlReferrer.PathAndQuery.ToString();
return parameters
}

Upvotes: 1

Sevin7
Sevin7

Reputation: 6492

EDIT: I just realized what I'm doing is actually redundant as the ajax request already includes a header called Referer. I'm leaving the code below as it is still valid if you want to pass a custom header and then access it on the server.

HttpContext.Current.Handler //This is null when using a web service

My work around is to add a custom header to all web service calls (using Jquery .ajax). The header contains the URL of the calling page:

$.ajaxSetup({
    headers: { 'CurrentUrl': '' + document.URL + '' }
});

Then on the server get the custom header inside of your web method:

HttpContext.Current.Request.Headers["CurrentUrl"]

The main reason I want the URL of the caller page is I use querystring parameters for debugging. The line below will give you all query string parameters from the page that called the web service.

HttpUtility.ParseQueryString(new Uri(HttpContext.Current.Request.Headers["CurrentUrl"]).Query)

Upvotes: 1

Rosita
Rosita

Reputation: 51

To get information of the client's previews request to current website you can use the UrlReferrer as follow:

//To get the Absolute path of the URI use this
string myPreviousAbsolutePath = Page.Request.UrlReferrer.AbsolutePath;

//To get the Path and Query of the URI use this
string myPreviousPathAndQuery = Page.Request.UrlReferrer.PathAndQuery;

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

Your question is not very clear. If you are trying to get the URL of the ASPX page calling the web service then you can't do this unless you pass it as argument to your web method or some custom HTTP header. Here's an example of a call:

var proxy = new YourWebServiceProxy();
string currentUrl = HttpContext.Current.Request.Url.ToString();
proxy.ValidateCode("some code", currentUrl);

and your web service method now looks like this:

[WebMethod]
public string ValidateCode(string sCode, string callerUrl)
{
    ...
}

Upvotes: 5

Ramesh
Ramesh

Reputation: 13266

If you are in .asmx webservice and needs to get the current url, you can try the below.

HttpContext.Current.Request.Url

Upvotes: 18

Related Questions