public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { if (this.automaticFormatSelectionEnabled) { MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties; if (messageProperties.ContainsKey(WebHttpDispatchOperationSelector.HttpOperationNamePropertyName)) { string operationName = messageProperties[WebHttpDispatchOperationSelector.HttpOperationNamePropertyName] as string; if (!string.IsNullOrEmpty(operationName) && this.formatters.ContainsKey(operationName)) { string acceptHeader = WebOperationContext.Current.IncomingRequest.Accept; if (!string.IsNullOrEmpty(acceptHeader)) { if (TrySetFormatFromCache(operationName, acceptHeader) || TrySetFormatFromAcceptHeader(operationName, acceptHeader, true /* matchCharSet */) || TrySetFormatFromAcceptHeader(operationName, acceptHeader, false /* matchCharSet */)) { return(null); } } if (TrySetFormatFromContentType(operationName)) { return(null); } SetFormatFromDefault(operationName); } } } return(null); }
private Encoding GetResponseMessageEncoding() { HttpRequestMessageProperty httpRequest = null; MessageProperties inMsgProperties = OperationContext.Current.IncomingMessageProperties; if (inMsgProperties.ContainsKey(HttpRequestMessageProperty.Name)) { httpRequest = (HttpRequestMessageProperty)inMsgProperties[HttpRequestMessageProperty.Name]; } Encoding encoding = Encoding.UTF8; string charset = null; if (httpRequest != null) { charset = httpRequest.Headers[HttpRequestHeader.AcceptCharset]; } if (charset != null) { encoding = Encoding.GetEncoding(charset); } return(encoding); }
/// <summary> /// 获取客户端IP地址 /// </summary> /// <returns>客户端IP地址</returns> private string GetClientIp() { string ip = null; #region # WCF获取 if (OperationContext.Current != null) { MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties; if (messageProperties.ContainsKey(RemoteEndpointMessageProperty.Name)) { object messageProperty = messageProperties[RemoteEndpointMessageProperty.Name]; RemoteEndpointMessageProperty remoteEndpointMessageProperty = (RemoteEndpointMessageProperty)messageProperty; ip = remoteEndpointMessageProperty.Address; } } if (!string.IsNullOrWhiteSpace(ip)) { return(ip); } #endregion #region # WebApi获取 #if NET45_OR_GREATER if (OwinContextReader.Current != null) { ip = OwinContextReader.Current.Request.RemoteIpAddress; } if (!string.IsNullOrWhiteSpace(ip)) { return(ip); } #endif #if NETSTANDARD2_0_OR_GREATER if (OwinContextReader.Current != null) { ip = OwinContextReader.Current.Connection.RemoteIpAddress.ToString(); } if (!string.IsNullOrWhiteSpace(ip)) { return(ip); } #endif #endregion #region # 本机 if (string.IsNullOrWhiteSpace(ip)) { ip = "localhost"; } #endregion return(ip); }
private static RemoteEndpointMessageProperty GetRemoteEndpointMessageProperty(OperationContext context) { MessageProperties properties = context.IncomingMessageProperties; if (!properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { return(null); } RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; return(endpoint); }
private void GetPropertiesFromMessageCore(Message message, MessageDescription messageDescription, object[] parameters) { MessageProperties properties = message.Properties; MessagePropertyDescriptionCollection propertyDescriptions = messageDescription.Properties; for (int i = 0; i < propertyDescriptions.Count; i++) { MessagePropertyDescription propertyDescription = propertyDescriptions[i]; if (properties.ContainsKey(propertyDescription.Name)) { parameters[propertyDescription.Index] = properties[propertyDescription.Name]; } } }
public static string GetClientIPAddress() { MessageProperties properties = OperationContext.Current.IncomingMessageProperties; if (properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; return(endpoint.Address); } else { return(properties.Via.Host); } }
private static string GetRequestUri() { QueryCompositionMessageProperty queryCompositionMessageProperty = null; MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties; var message = OperationContext.Current.RequestContext.RequestMessage; var httpRequest = message.ToHttpRequestMessage(); if (httpRequest != null) { if (messageProperties.ContainsKey(QueryCompositionMessageProperty.Name)) { queryCompositionMessageProperty = messageProperties[QueryCompositionMessageProperty.Name] as QueryCompositionMessageProperty; return(queryCompositionMessageProperty.RequestUri); } return(httpRequest.RequestUri.AbsoluteUri); } else { if (messageProperties.ContainsKey(QueryCompositionMessageProperty.Name)) { queryCompositionMessageProperty = messageProperties[QueryCompositionMessageProperty.Name] as QueryCompositionMessageProperty; return(queryCompositionMessageProperty.RequestUri); } else { UriTemplateMatch uriTemplateMatch = WebOperationContext.Current.IncomingRequest.UriTemplateMatch; if (uriTemplateMatch != null && uriTemplateMatch.RequestUri != null && uriTemplateMatch.RequestUri.AbsoluteUri != null) { return(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.AbsoluteUri); } } } return(null); }
private async Task <ServerResponse> OnlyRunOnIntranet(Func <Task <ServerResponse> > func) { if (Properties.Settings.Default.EnableTesting) { return(await func()); } try { string ip = null; MessageProperties prop = OperationContext.Current?.IncomingMessageProperties; if (prop != null) { if (prop.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; if (endpoint != null) { ip = endpoint.Address; } } } if (ip == null) { ip = HttpContext.Current.Request.UserHostAddress; } if (ip == null) { throw new ResultCodeException(ResultCodes.SystemError, ("en", "Unable to get incoming ip"), ("es", "No puedo obtener el ip de origen")); } if (IsIntranet(ip)) { return(await func()); } throw new ResultCodeException(ResultCodes.Forbidden, ("en", "Not allowed to request from Internet"), ("es", "No se puede llamar a este servicio desde internet")); } catch (Exception e) { ServerResponse s = new ServerResponse(); s.PopulateFromException(e, Logger); return(s); } }
public string GetSessionKey() { string key = string.Empty; OperationContext context = OperationContext.Current; if (context != null) { MessageProperties prop = context.IncomingMessageProperties; if (prop != null && !string.IsNullOrEmpty(RemoteEndpointMessageProperty.Name) && prop.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; key = endpoint.Address; // + ":" + endpoint.Port; } } else { Logger.LogError("No Context"); } return(key); }
public static bool ExtractRemoteEndpointAddress(MessageProperties properties, out string address) { if (properties == null) throw new ArgumentNullException(nameof(properties)); address = null; if (properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { var remoteEndpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; if (!String.IsNullOrEmpty(remoteEndpoint?.Address)) { address = remoteEndpoint.Address; return true; } } return false; }
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { WebOperationContext currentContext = WebOperationContext.Current; OutgoingWebResponseContext outgoingResponse = null; if (currentContext != null) { outgoingResponse = currentContext.OutgoingResponse; } WebMessageFormat format = this.defaultFormat; if (outgoingResponse != null) { WebMessageFormat?nullableFormat = outgoingResponse.Format; if (nullableFormat.HasValue) { format = nullableFormat.Value; } } if (!this.formatters.ContainsKey(format)) { string operationName = "<null>"; if (OperationContext.Current != null) { MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties; if (messageProperties.ContainsKey(WebHttpDispatchOperationSelector.HttpOperationNamePropertyName)) { operationName = messageProperties[WebHttpDispatchOperationSelector.HttpOperationNamePropertyName] as string; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.OperationDoesNotSupportFormat, operationName, format.ToString()))); } if (outgoingResponse != null && string.IsNullOrEmpty(outgoingResponse.ContentType)) { string automatedSelectionContentType = outgoingResponse.AutomatedFormatSelectionContentType; if (!string.IsNullOrEmpty(automatedSelectionContentType)) { // Don't set the content-type if it is default xml for backwards compatiabilty if (!string.Equals(automatedSelectionContentType, defaultContentTypes[WebMessageFormat.Xml], StringComparison.OrdinalIgnoreCase)) { outgoingResponse.ContentType = automatedSelectionContentType; } } else { // Don't set the content-type if it is default xml for backwards compatiabilty if (format != WebMessageFormat.Xml) { outgoingResponse.ContentType = defaultContentTypes[format]; } } } Message message = this.formatters[format].SerializeReply(messageVersion, parameters, result); return(message); }
public Stream InvokeMethod(Stream Params) { String ipAddress = ""; OperationContext context = OperationContext.Current; MessageProperties properties = context.IncomingMessageProperties; if (properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; ipAddress = string.Format("{0}:{1}", endpoint.Address, endpoint.Port); } List <string> parameters = new List <string>(); try { ApplicationContext AppContext = ApplicationContext.Current; AppContext.Identification.IPAddress = ipAddress; LoginLog(AppContext); } catch (Exception ex) { logger.Error("log login:"******""; try { Stream ms = ReadMemoryStream(Params); //Params.Dispose(); Stream unzipstream = Yqun.Common.Encoder.Compression.DeCompressStream(ms); //ms.Dispose(); Hashtable paramsList = Yqun.Common.Encoder.Serialize.DeSerializeFromStream(unzipstream) as Hashtable; //unzipstream.Dispose(); string path = ServerLoginInfos.DBConnectionInfo.LocalStartPath; parameters.Add(path); string Assembly_Name = paramsList["assembly_name"].ToString(); parameters.Add(Assembly_Name); string FileName = Path.Combine(path.Trim(), Assembly_Name.Trim()); parameters.Add(FileName); Method_Name = paramsList["method_name"].ToString(); Method_Paremeters = paramsList["method_paremeters"] as object[]; object o = InvokeMethod(FileName, Method_Name, Method_Paremeters); Hashtable t = new Hashtable(); t.Add("return_value", o); Stream stream = Serialize.SerializeToStream(t); Stream zipstream = Compression.CompressStream(stream); //stream.Dispose(); return(zipstream); } catch (Exception ex) { String log = ""; foreach (var item in Method_Paremeters) { log += item.ToString() + ";"; } logger.Error(string.Format("[{0}]访问服务出错,原因为“{1}”,参数列表为{2}, 传入参数为{3},方法名称{4}", ApplicationContext.Current.UserName, ex.Message, string.Join(",", parameters.ToArray()), log, Method_Name )); } return(null); }
//Implements #region # 登录 —— LoginInfo Login(string loginId, string password) /// <summary> /// 登录 /// </summary> /// <param name="loginId">登录名</param> /// <param name="password">密码</param> /// <returns>登录信息</returns> public LoginInfo Login(string loginId, string password) { #region # 验证参数 if (string.IsNullOrWhiteSpace(loginId)) { throw new ArgumentNullException(nameof(loginId), "用户名不可为空!"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException(nameof(password), "密码不可为空!"); } #endregion lock (_Sync) { /****************验证机器****************/ this.AuthenticateMachine(); /****************登录验证****************/ User currentUser = this._repMediator.UserRep.SingleOrDefault(loginId); #region # 验证 if (currentUser == null) { throw new InvalidOperationException($"用户名\"{loginId}\"不存在!"); } if (!currentUser.Enabled) { throw new InvalidOperationException("用户已停用!"); } if (currentUser.Password != password.ToMD5()) { throw new InvalidOperationException("登录失败,密码错误!"); } #endregion //生成公钥 Guid publicKey = Guid.NewGuid(); //生成登录信息 LoginInfo loginInfo = new LoginInfo(currentUser.Number, currentUser.Name, publicKey); #region # 登录信息的信息系统部分/菜单部分/权限部分 ICollection <Guid> roleIds = this._repMediator.RoleRep.FindIds(loginId, null); /*信息系统部分*/ IEnumerable <string> systemNos = currentUser.GetInfoSystemNos(); IDictionary <string, InfoSystem> systems = this._repMediator.InfoSystemRep.Find(systemNos); loginInfo.LoginSystemInfos.AddRange(systems.Values.Select(x => x.ToLoginSystemInfo())); /*菜单部分*/ IEnumerable <Guid> authorityIds = this._repMediator.AuthorityRep.FindIdsByRole(roleIds); IEnumerable <Menu> menus = this._repMediator.MenuRep.FindByAuthority(authorityIds, null); menus = menus.TailRecurseParentNodes(); ICollection <LoginMenuInfo> menuTree = menus.ToTree(null); loginInfo.LoginMenuInfos.AddRange(menuTree); /*权限部分*/ IEnumerable <Authority> authorities = this._repMediator.AuthorityRep.FindByRole(roleIds); loginInfo.LoginAuthorityInfos = authorities.GroupBy(x => x.SystemNo).ToDictionary(x => x.Key, x => x.Select(y => y.ToLoginAuthorityInfo()).ToArray()); #endregion //以公钥为键,登录信息为值,存入分布式缓存 CacheMediator.Set(publicKey.ToString(), loginInfo, DateTime.Now.AddMinutes(_Timeout)); //获取客户端IP MessageProperties properties = OperationContext.Current.IncomingMessageProperties; string ip = "localhost"; if (properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty endpoint = (RemoteEndpointMessageProperty)properties[RemoteEndpointMessageProperty.Name]; ip = endpoint.Address; } //生成登录记录 this.GenerateLoginRecord(publicKey, ip, currentUser.Number, currentUser.Name); return(loginInfo); } }