简体   繁体   中英

ASP.NET: Getting the Current URL via a Web Method?

I'm trying to retrieve the URL of the current page via a Web Method. The code below works well on a normal C# Method such as the Page_Load but does not work inside a Web Method.

[WebMethod(EnableSession=true)]
public static void UpdateProjectName(string name)
{
        string project_id = HttpContext.Current.Request.Url.ToString();
}

I'm receiving an empty string ("") as the project_id. What am I doing wrong?

You need this:

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

Try to do next code:

[WebMethod(EnableSession=true)]
public static void UpdateProjectName(string name)
{
        string project_id = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
}

Url is just object, that's why it returns empty value to you. AbsoluteUri will give a full URL of current page. Example: http://yourweb.site/Admin.aspx?id=15&time=yesterday

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;

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