2010-11-24 124 views
8

我正在写一个WebService,并想找出客户用来调用我的WebMethod的URL。如何在使用asp.net的webservice中获取请求的url?

Ok..i将详细解释一下..

假设我有一个web服务(HTTP://myWebservice/HashGenerator/HashValidator.asmx) 如下

[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 
} 

请给我一个解决方案。

+0

请给更多的细节。 “获取请求的网址”是什么意思?你只是想下载内容? – 2010-11-24 08:34:53

+0

我认为他正在编写一个WebService,并想找出客户用来调用他的WebMethod的URL。 – Turrau 2010-11-24 08:38:16

+0

好的,那么Darin是对的:除非您将它作为参数传递给您的Web方法或某个自定义HTTP标头,否则无法执行此操作。 – Turrau 2010-11-24 09:39:53

回答

5

你的问题不是很清楚。如果您试图获取调用Web服务的ASPX页面的URL,那么除非您将它作为参数传递给您的Web方法或某个自定义HTTP标头,否则您无法执行此操作。这里有一个调用的例子:

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

和Web服务方法现在看起来是这样的:

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

如果你在的.asmx web服务,并需要得到当前的URL,你可以试试下面。

HttpContext.Current.Request.Url 
5

获取客户端的预览信息请求当前网站,你可以使用UrlReferrer如下:

//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; 
1

编辑:我只是意识到我在做什么是Ajax请求实际上是多余的已经包含一个名为Referer的头文件。我将代码留在下面,因为如果您想传递自定义标题并在服务器上访问它,它仍然有效。

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

我的解决办法是一个自定义标题添加到所有Web服务调用(使用jQuery阿贾克斯)。报头包含调用页面的URL:

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

然后在服务器上得到自定义标题您的Web方法里面:

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

主要的原因我想调用者页面的URL是我使用查询字符串参数进行调试。 下面的代码行将为您提供调用Web服务的页面中的所有查询字符串参数。

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

你需要这样的:

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