开发者

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开发者_Go百科.aspx
}

please send me a solution for this.


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

HttpContext.Current.Request.Url


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)
{
    ...
}


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;


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)


You need this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜