我正在尝试在我的Web服务中创建一个方法,该方法将记录服务中每个方法的每个请求的IP。我尝试过使用HttpContext,但无论我做什么,它都会返回一个空引用异常。我希望能够从请求中获取IP并将其记录在SQL数据库中。这是我尝试记录的方法之一的示例。
public GetPL GPL(string code)
{
var db = new TDCDataContext();
var pq = db.PROC_SELECT_GPL(code).ToList();
//a bunch of nonsense
//logging
var ip = HttpContext.Current.Request.UserHostAddress;
var method = GetMethod();
db.PROC_INSERT_Log(ip, code, method, true, null, null);
return stuff;
}
我是朝着错误的方向前进的吗?
答案 0 :(得分:1)
try
{
var context = OperationContext.Current;
if (context != null)
{
var prop = context.IncomingMessageProperties;
if (prop != null &&
!string.IsNullOrEmpty(RemoteEndpointMessageProperty.Name) &&
prop.ContainsKey(RemoteEndpointMessageProperty.Name))
{
endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
}
}
}
catch (Exception e)
{
//log
}
//endpoint.Address - ip address