简体   繁体   中英

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.

如果您在.asmx webservice并需要获取当前网址,可以尝试以下方法。

HttpContext.Current.Request.Url

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;

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM