jbatista jbatista - 1 month ago 6
C# Question

How to get a webservice's own endpoint in C#?

I have a C# webservice, as such:

namespace MyProject
{
#region "Frontend"

[WebService(Name="MyWebservice")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyWsClass : System.Web.Services.WebService
{
private static readonly IRegisterer reg = new SelfRegisterInDatabase();

private MyWsClass()
{
// tell who I am to a database
MyWsClass.reg.SelfRegister();
}

// A service I expose to the users
[WebMethod]
public object MyMethod(object in)
{
// do some work
return new Object();
}
}

#endregion

#region "Backend"

public interface IRegisterer
{
public void SelfRegister();
}

// Herein lies my question:
public class SelfRegisterInDatabase : IRegisterer
{
private static volatile bool IsRegistered = false;

public void SelfRegister()
{
if(!IsRegistered)
{
// Expecting something like: "http://THEHOST:THEPORT/MyWebservice.aspx?WSDL"
// In principle, the variable part is "THEHOST:THEPORT".
string EndpointUrl =
"HOW_DO_I_GET_WEBSERVICE_ENDPOINT_URL_HERE???"
;

// 1) open a Database connection;
// 2) insert new entry for this EndpointUrl string if doesn't exist;
// 3) and close DB connection
SelfRegisterInDatabase.IsRegistered = true;
}
return;
}
}
#endregion
}


I would like to know how can I dynamically read the webservice get its own endpoint so that I can have it register in a database (say, SQL Server -- the actual
INSERT
ing is not what I'm asking about here). Which method/configuration should I use?

Answer

Try this to get the entire endpoint String:

WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.OriginalString

You'll need

using System.ServiceModel.Web;