private string GetAcceptLanguage(WebOperationContext webOperationContext) { string languageValue = webOperationContext.IncomingRequest.Headers["X-Accept-Language-Override"]; if (languageValue == null || languageValue.Trim() == String.Empty) { languageValue = webOperationContext.IncomingRequest.Headers["Accept-Language"]; } if (languageValue != null) { string[] array = languageValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = array.Length; i > 0; i--) { string str = array[i - 1].ToLower(); switch (str) { case "en": case "en-us": return "en-US"; case "zh": case "zh-chs": case "zh-cn": return "zh-CN"; case "zh-cht": case "zh-tw": return "zh-TW"; } } } return "en-US"; }
public SamplePushUserRegistrationService(HttpContextBase context, WebOperationContext webOperationContext, IFormsAuthentication formsAuth, IMembershipService membershipService, IPushUserEndpointsRepository pushUserEndpointsRepository) { if ((context == null) && (HttpContext.Current == null)) { throw new ArgumentNullException("context", "Context cannot be null if not running on a Web context."); } if (pushUserEndpointsRepository == null) { throw new ArgumentNullException("pushUserEndpointsRepository", "PushUserEndpoints repository cannot be null."); } if (formsAuth == null) { throw new ArgumentNullException("formsAuth", "Forms Authentication service cannot be null."); } if (membershipService == null) { throw new ArgumentNullException("membershipService", "Membership service cannot be null."); } this.webOperationContext = webOperationContext; this.context = context; this.pushUserEndpointsRepository = pushUserEndpointsRepository; this.formsAuth = formsAuth; this.membershipService = membershipService; }
static IDictionary<string, object> CreateOwinEnvironment(WebOperationContext webRequest, Stream requestBody) { var incomingRequest = webRequest.IncomingRequest; var baseUri = incomingRequest.UriTemplateMatch.BaseUri; var requestUri = incomingRequest.UriTemplateMatch.RequestUri; var baseUriPathUnescaped = "/" + baseUri.GetComponents(UriComponents.Path, UriFormat.Unescaped); var requestUriPathUnescaped = "/" + requestUri.GetComponents(UriComponents.Path, UriFormat.Unescaped); var pathBase = baseUriPathUnescaped.TrimEnd('/'); var path = requestUriPathUnescaped.Substring(pathBase.Length); var queryString = requestUri.Query.TrimStart('?'); var headers = incomingRequest.Headers.AllKeys .ToDictionary(key => key, incomingRequest.Headers.Get); var env = new Dictionary<string, object>(); new Environment(env) { Version = "1.0", Method = incomingRequest.Method, Scheme = requestUri.Scheme, PathBase = pathBase, Path = path, QueryString = queryString, Headers = headers, Body = Body.FromStream(requestBody), }; return env; }
public NetHttpContext(WebOperationContext context, out Stream stream) { this.context = context; this.request = new NetHttpServiceRequest(context.IncomingRequest); this.response = new NetHttpServiceRespone(context.OutgoingResponse, out stream); }
public WebOperationContextWrapper(WebOperationContext context) { if (context == null) { throw new ArgumentNullException("context"); } this.context = context; }
public void AddEntry(SyndicationItemFormatter item) { WebOperationContext context = WebOperationContext.Current; // Add entry // .. context.OutgoingResponse.StatusCode = HttpStatusCode.Created; context.OutgoingResponse.StatusDescription = String.Format("Syndication item added with title '{0}'", item.Item.Title.Text); }
public SharedAccessSignatureService(CloudBlobClient cloudBlobClient, WebOperationContext webOperationContext) { if ((cloudBlobClient == null) && (GetStorageAccountFromConfigurationSetting() == null)) { throw new ArgumentNullException("cloudBlobClient", "The Cloud Blob Client cannot be null if no configuration is loaded."); } this.cloudBlobClient = cloudBlobClient ?? GetStorageAccountFromConfigurationSetting().CreateCloudBlobClient(); this.webOperationContext = webOperationContext; }
public System.ServiceModel.Channels.Message AllRestFulMessages1(System.ServiceModel.Channels.Message message) { WebOperationContext context = WebOperationContext.Current; Uri uri = context.IncomingRequest.UriTemplateMatch.RequestUri; NameValueCollection queryString = context.IncomingRequest.UriTemplateMatch.QueryParameters; System.ServiceModel.Channels.Message response = System.ServiceModel.Channels.Message.CreateMessage( System.ServiceModel.Channels.MessageVersion.None, "*", "Simple response string"); return(response); }
public UnitContract GetUnit(ushort id) { log.Debug("GetUnit: " + id); WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.Headers.Add("type", "unit"); return(WebServiceModule.OmniLink.Controller.Units[id].ToContract()); }
public AreaContract GetArea(ushort id) { log.Debug("GetArea: {id}", id); WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.Headers.Add("type", "area"); return(WebServiceModule.OmniLink.Controller.Areas[id].ToContract()); }
public ThermostatContract GetThermostat(ushort id) { log.Debug("GetThermostat: {id}", id); WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.Headers.Add("type", "thermostat"); return(WebServiceModule.OmniLink.Controller.Thermostats[id].ToContract()); }
/// <summary> /// Map this manufactured material to FHIR /// </summary> protected override Medication MapToFhir(ManufacturedMaterial model, WebOperationContext webOperationContext) { var retVal = DataTypeConverter.CreateResource <Medication>(model); // Code of medication code retVal.Code = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty <Concept>("TypeConcept")); if (model.StatusConceptKey == StatusKeys.Active) { retVal.Status = SubstanceStatus.Active; } else if (model.StatusConceptKey == StatusKeys.Obsolete) { retVal.Status = SubstanceStatus.Inactive; } else if (model.StatusConceptKey == StatusKeys.Nullified) { retVal.Status = SubstanceStatus.Nullified; } // Is brand? retVal.IsBrand = false; retVal.IsOverTheCounter = model.Tags.Any(o => o.TagKey == "isOtc"); var manufacturer = model.LoadCollection <EntityRelationship>("Relationships").FirstOrDefault(o => o.RelationshipTypeKey == EntityRelationshipTypeKeys.WarrantedProduct); if (manufacturer != null) { retVal.Manufacturer = DataTypeConverter.CreateReference <MARC.HI.EHRS.SVC.Messaging.FHIR.Resources.Organization>(manufacturer.LoadProperty <Entity>("TargetEntity"), webOperationContext); } // Form retVal.Form = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty <Concept>("FormConcept"), "http://hl7.org/fhir/ValueSet/medication-form-codes"); retVal.Package = new MARC.HI.EHRS.SVC.Messaging.FHIR.Backbone.MedicationPackage(); retVal.Package.Batch = new MARC.HI.EHRS.SVC.Messaging.FHIR.Backbone.MedicationBatch() { LotNumber = model.LotNumber, Expiration = model.ExpiryDate }; // Picture of the object? var photo = model.LoadCollection <EntityExtension>("Extensions").FirstOrDefault(o => o.ExtensionTypeKey == ExtensionTypeKeys.JpegPhotoExtension); if (photo != null) { retVal.Image = new MARC.HI.EHRS.SVC.Messaging.FHIR.DataTypes.Attachment() { ContentType = "image/jpg", Data = photo.ExtensionValueXml } } ; return(retVal); }
/// <summary> /// 加载个人评论(个人中心:我的跟帖) /// </summary> /// <param name="userId"></param> /// <param name="page"></param> /// <param name="pagesize"></param> /// <returns></returns> public Stream LoadUserContent(string userId, string page, string pagesize) { // 得到上下文 WebOperationContext woc = WebOperationContext.Current; // 设置响应格式,消除了返回为string的有反斜杠情况 woc.OutgoingResponse.ContentType = "application/json; charset=utf-8"; string json = ""; // 根据条件获得评论 List <CommentInfo> cmtLst = DataAccess_News.Comments_SelectPaged(userId, page, pagesize); // 在评论里加上作者、发表时间、以及文章标题 List <CommentInfoApp> cmtLst2 = new List <CommentInfoApp>(); if (cmtLst != null) { for (int i = 0; i < cmtLst.Count; i++) { var item = cmtLst[i]; var infoApp = new CommentInfoApp(); infoApp.cmt_content = item.cmt_content; infoApp.cmt_id = item.cmt_id; infoApp.cmt_sourceId = item.cmt_sourceId; infoApp.cmt_sourceType = item.cmt_sourceType; infoApp.cmt_uid = item.cmt_uid; infoApp.cmt_sourceCateId = item.cmt_sourceCateId; int catId = 0; if (!int.TryParse(item.cmt_sourceCateId, out catId)) { continue; } var cate = CacheMarker.GetNewsCatesBycat_id(catId.ToString()); if (cate == null) { continue; } NewsInfo news = CacheMarker.News_Selectbyn_gid(item.cmt_sourceId, "News_" + cate.cat_tableIndex.ToString()); if (news != null) { infoApp.n_authors = news.n_authors; infoApp.n_date = news.n_date; infoApp.n_title = news.n_title; } cmtLst2.Add(infoApp); } } var jsonSerialiser = new JavaScriptSerializer(); json = "{\"list\":" + jsonSerialiser.Serialize(cmtLst2) + "}"; return(new MemoryStream(Encoding.UTF8.GetBytes(json))); }
/// <summary> /// Map the substance to FHIR /// </summary> protected override Substance MapToFhir(Material model, WebOperationContext webOperationContext) { var retVal = DataTypeConverter.CreateResource <Substance>(model); // Identifiers retVal.Identifier = model.Identifiers.Select(o => DataTypeConverter.ToFhirIdentifier <Entity>(o)).ToList(); // sTatus if (model.StatusConceptKey == StatusKeys.Active) { retVal.Status = SubstanceStatus.Active; } else if (model.StatusConceptKey == StatusKeys.Nullified) { retVal.Status = SubstanceStatus.Nullified; } else if (model.StatusConceptKey == StatusKeys.Obsolete) { retVal.Status = SubstanceStatus.Inactive; } // Category and code if (model.LoadProperty <Concept>("TypeConcept").ConceptSetsXml.Any(o => o == ConceptSetKeys.VaccineTypeCodes)) { retVal.Category = new MARC.HI.EHRS.SVC.Messaging.FHIR.DataTypes.FhirCodeableConcept(new Uri("http://hl7.org/fhir/substance-category"), "drug"); } else { retVal.Category = new MARC.HI.EHRS.SVC.Messaging.FHIR.DataTypes.FhirCodeableConcept(new Uri("http://hl7.org/fhir/substance-category"), "material"); } retVal.Code = DataTypeConverter.ToFhirCodeableConcept(model.LoadProperty <Concept>("TypeConcept"), "http://hl7.org/fhir/ValueSet/substance-code"); retVal.Description = model.LoadCollection <EntityName>("Names").FirstOrDefault(o => o.NameUseKey == NameUseKeys.OfficialRecord)?.LoadCollection <EntityNameComponent>("Components")?.FirstOrDefault()?.Value; // TODO: Instance or kind if (model.DeterminerConceptKey == DeterminerKeys.Specific) { var conceptRepo = ApplicationContext.Current.GetService <IConceptRepositoryService>(); retVal.Instance = new List <MARC.HI.EHRS.SVC.Messaging.FHIR.Backbone.SubstanceInstance>() { new MARC.HI.EHRS.SVC.Messaging.FHIR.Backbone.SubstanceInstance() { Expiry = model.ExpiryDate, Quantity = new MARC.HI.EHRS.SVC.Messaging.FHIR.DataTypes.FhirQuantity() { Units = model.QuantityConceptKey.HasValue ? conceptRepo.GetConceptReferenceTerm(model.QuantityConceptKey.Value, "UCUM").Mnemonic : null, Value = model.Quantity } } }; } return(retVal); }
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) { WebOperationContext context = WebOperationContext.Current; string cacheControl = context.IncomingRequest.Headers["Cache-Control"]; if (cacheControl != null && cacheControl.ToLower() == "no-cache") { context.OutgoingResponse.Headers["Cache-Control"] = "No-Cache"; } }
public Stream ReturnAnyXml() { WebOperationContext CurrentWebContext = WebOperationContext.Current; if (CurrentWebContext != null) { CurrentWebContext.OutgoingResponse.ContentType = "text/xml"; String AnyXml = "<tag></tag>"; return(new MemoryStream(Encoding.UTF8.GetBytes(AnyXml))); } }
Stream ValidationResponseStream(WebOperationContext ctx, AzureEventGridEvent validationEvent) { string validationCode = (string)((JObject)validationEvent.Data)["validationCode"]; ctx.OutgoingResponse.ContentType = "application/json"; string responseBody = "{\"validationResponse\": \"" + validationCode + "\"}"; Stream output = new MemoryStream(Encoding.UTF8.GetBytes(responseBody)); output.Position = 0; return(output); }
public Result CrossDomain(string name, string no) { WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*"); return(new Result() { Name = name, No = no }); }
public ElevationResponse OtherUris(Message msg) { WebOperationContext webOperationContext = WebOperationContext.Current; IncomingWebRequestContext incomingWebRequestContext = webOperationContext.IncomingRequest; string uri = incomingWebRequestContext.UriTemplateMatch.RequestUri.ToString(); Console.WriteLine("{0}: Request caugth by OtherUris: {1}", DateTime.Now, uri); logger.Info("Request caugth by AllURIs: {0}", uri); return(new ElevationResponse(ElevationResponses.KO, null)); }
/// <summary> /// Initializes a new System.Data.Services.HttpContextServiceHost instance. /// </summary> /// <param name='messageBody'>Incoming message body to process.</param> internal HttpContextServiceHost(Stream messageBody) { // We capture the current context at initialization time rather // than accessing it repeatedly. this.incomingMessageBody = messageBody; this.operationContext = WebOperationContext.Current; if (this.operationContext == null) { throw new InvalidOperationException(Strings.HttpContextServiceHost_WebOperationContextCurrentMissing); } }
public static void Snippet3() { // <Snippet3> WebOperationContext current = WebOperationContext.Current; Console.WriteLine("Incoming Response"); Console.WriteLine("ContentLength: " + current.IncomingResponse.ContentLength); Console.WriteLine("ContentType: " + current.IncomingResponse.ContentType); Console.WriteLine("StatusCode: " + current.IncomingResponse.StatusCode); // </Snippet3> }
/// <summary> /// Initializes a new Microsoft.OData.Service.HttpContextServiceHost instance. /// </summary> /// <param name='messageBody'>Incoming message body to process.</param> internal HttpContextServiceHost(Stream messageBody) { // We capture the current context at initialization time rather // than accessing it repeatedly. this.incomingMessageBody = messageBody; this.operationContext = WebOperationContext.Current; // DataService<>.ProcessRequestForMessage already checks for this. // Hence there is no need to check for this again. Debug.Assert(this.operationContext != null, "this.operationContext != null"); }
//One of the two main entry points into the encoder. Called by WCF to encode a Message into a buffered byte array. public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { //Use the inner encoder to encode a Message into a buffered byte array ArraySegment <byte> buffer = innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset); WebOperationContext context = WebOperationContext.Current; OutgoingWebResponseContext responseContext = WebOperationContext.Current.OutgoingResponse; bool compressResponse = OperationContext.Current.Extensions.OfType <CompressOutputExtension>().Any(); return(compressResponse ? CompressBuffer(buffer, bufferManager, messageOffset) : buffer); }
/// <summary> /// Initializes a new System.Data.Services.HttpContextServiceHost instance. /// </summary> /// <param name='messageBody'>Incoming message body to process.</param> internal HttpContextServiceHost(Stream messageBody) { // We capture the current context at initialization time rather // than accessing it repeatedly. this.incomingMessageBody = messageBody; this.operationContext = WebOperationContext.Current; if (this.operationContext == null) { throw new InvalidOperationException(Strings.HttpContextServiceHost_WebOperationContextCurrentMissing); } }
public void Retrait(string mail, string hashPwd, string compteId, int montant) { Compte compte = null; WebOperationContext context = WebOperationContext.Current; int compteIdInt; if (!Int32.TryParse(compteId, out compteIdInt)) { context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; context.OutgoingResponse.StatusDescription = "Probleme numero de compte"; return; } int id = isAutenticated(mail, hashPwd); if (id > 0) { using (eBanqueContext dbContext = new eBanqueContext()) { compte = dbContext.Comptes.FirstOrDefault(c => c.Proprietaire.Id == id && c.Id == compteIdInt); if (compte == null) { context.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; context.OutgoingResponse.StatusDescription = "Compte introuvable"; } else { if (compte.Solde - montant < decouvertPossible) { context.OutgoingResponse.StatusCode = HttpStatusCode.NotAcceptable; context.OutgoingResponse.StatusDescription = "Fonds insufisant"; } else { compte.Solde -= montant; compte.Historique.Add(new Operation { Date = DateTime.Today, Montant = montant, Type = TypeOperation.Retrait, CompteProprietaire = compte }); dbContext.SaveChanges(); context.OutgoingResponse.StatusCode = HttpStatusCode.OK; context.OutgoingResponse.StatusDescription = "Retrait de " + montant + "€ effectué"; } } } } else { context.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; context.OutgoingResponse.StatusDescription = "Utilisateur introuvable"; } }
/// <summary> /// Initializes a new Microsoft.OData.Service.HttpContextServiceHost instance. /// </summary> /// <param name='messageBody'>Incoming message body to process.</param> internal HttpContextServiceHost(Stream messageBody) { // We capture the current context at initialization time rather // than accessing it repeatedly. this.incomingMessageBody = messageBody; this.operationContext = WebOperationContext.Current; // DataService<>.ProcessRequestForMessage already checks for this. // Hence there is no need to check for this again. Debug.Assert(this.operationContext != null, "this.operationContext != null"); }
public static WebFaultException <T> CreateWebFault <T>(this WebOperationContext context, HttpStatusCode code, string reason, T payload, IEnumerable <Type> knownTypes = null) { context.OutgoingResponse.StatusDescription = reason; if (knownTypes != null) { return(new WebFaultException <T>(payload, code)); } else { return(new WebFaultException <T>(payload, code, knownTypes)); } }
public Service1(IHeaders headers, IUrlParameters urlParameters, IRequestUri requestUri, OperationContext operationContext, WebOperationContext webOperationContext) { _Headers = headers; _UrlParameters = urlParameters; _RequestUri = requestUri; _OperationContext = operationContext; _WebOperationContext = webOperationContext; }
public Stream Echo(Stream message) { WebOperationContext context = WebOperationContext.Current; foreach (string headerName in context.IncomingRequest.Headers) { context.OutgoingResponse.Headers[headerName] = context.IncomingRequest.Headers[headerName]; } context.OutgoingResponse.StatusCode = HttpStatusCode.OK; return(message); }
void PrintRequest(WebOperationContext ctx, string body) { // Print headers and body of request to console string curTime = DateTime.Now.ToString("hh.mm.ss.fff"); Console.WriteLine($"Received a HTTP POST from EventGrid at time:{curTime}"); foreach (var header in ctx.IncomingRequest.Headers.AllKeys) { Console.WriteLine($"{header}: {ctx.IncomingRequest.Headers[header]}"); } Console.WriteLine(body); }
/// <summary> /// 服务端收到请求后 /// </summary> /// <param name="request"></param> /// <param name="channel"></param> /// <param name="instanceContext"></param> /// <returns></returns> public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { RedisHelper r = RedisHelper.GetRedisHelper(); string url = channel.LocalAddress.Uri.ToString(); WebOperationContext woc = WebOperationContext.Current;//http请求方式非WCF代理类调用下的检查方式 string s = request.ToString(); //获得当前请求头中的TokenID var tokenID = woc.IncomingRequest.Headers["TokenID"]; var uri = woc.IncomingRequest.UriTemplateMatch; if (uri != null) { var address = woc.IncomingRequest.UriTemplateMatch.RequestUri.ToString(); //请求为登录的时候不过滤 if (!address.EndsWith("LoginManage/Login")) { //redis判断 string user = r.StringGet(tokenID); if (string.IsNullOrEmpty(user)) { throw new Exception("tokenId$登录失效,请重新登录%"); } // if (tokenID != "admin")//redis判断 // { // woc.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.MethodNotAllowed; // // woc.OutgoingResponse.StatusDescription = "222"; // throw new Exception("tokenId$登录失效,请重新登录%"); // } } } else//WCF代理类调用下的检查方式 { OperationContext oc = OperationContext.Current; var headers = OperationContext.Current.IncomingMessageHeaders; var actionAddress = headers.Action; //1.请求为登录的时候不过滤 2.代理类生成时请求不过滤 if (!string.IsNullOrEmpty(actionAddress) && !actionAddress.EndsWith("ILoginManage/Login")) { var token = GetHeaderValue("TokenID"); string user = r.StringGet(token); if (string.IsNullOrEmpty(user)) { throw new Exception("tokenID失效,请重新登录"); } // if (token != "admin") //redis判断 // { // throw new Exception("请求无效!!!"); // } } } return(null); }
public ThermostatContract GetThermostat(ushort id) { Event.WriteVerbose("WebService", "GetThermostat: " + id); WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.Headers.Add("type", "thermostat"); clsThermostat unit = WebService.HAC.Thermostats[id]; return(Helper.ConvertThermostat(id, unit)); }
public AreaContract GetArea(ushort id) { Event.WriteVerbose("WebService", "GetArea: " + id); WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.Headers.Add("type", "area"); clsArea area = WebService.HAC.Areas[id]; return(Helper.ConvertArea(id, area)); }
public Language[] ReadLanguages() { WebOperationContext woc = WebOperationContext.Current; if (woc == null) { return(null); } woc.OutgoingResponse.StatusCode = HttpStatusCode.OK; return(Enum.GetValues(typeof(Language)).Cast <Language>().ToArray()); }
/// <summary> /// 获取热门评论 /// </summary> /// <param name="sourceId"></param> /// <param name="page"></param> /// <param name="limit"></param> /// <returns></returns> public Stream RecommendComments_SelectPaged2(string sourceId, string page, string limit) { // 得到上下文 WebOperationContext woc = WebOperationContext.Current; //设置响应格式,消除了返回为string的有反斜杠情况 woc.OutgoingResponse.ContentType = "application/json; charset=utf-8"; string json = CacheMarker.GetRecommendComments2(sourceId.ToSafety(), page, limit); return(new MemoryStream(Encoding.UTF8.GetBytes(json))); }
public static void Snippet2() { // <Snippet2> WebOperationContext current = WebOperationContext.Current; WebHeaderCollection headers = current.IncomingRequest.Headers; foreach (string name in headers) { Console.WriteLine(name + " " + headers.Get(name)); } // </Snippet2> }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="instance"></param> /// <returns></returns> public Blob Update(String id, Blob instance) { WebOperationContext webContext = WebOperationContext.Current; Guid g = new Guid(id); if (this.store.ContainsKey(g)) { this.store[g] = instance; } return(instance); }
public static Uri BindTemplateToRequestUri(this WebOperationContext context, UriTemplate template, params string[] values) { if (context == null) { throw new ArgumentNullException("context"); } if (template == null) { throw new ArgumentNullException("template"); } return(template.BindByPosition(context.IncomingRequest.UriTemplateMatch.BaseUri, values)); }
public SharedAccessSignatureService(CloudBlobClient cloudBlobClient, WebOperationContext webOperationContext, BlobContainerRequestValidator requestValidator, IUserPrivilegesRepository userPrivilegesRepository) { if ((cloudBlobClient == null) && (GetStorageAccountFromConfigurationSetting() == null)) { throw new ArgumentNullException("cloudBlobClient", "The Cloud Blob Client cannot be null if no configuration is loaded."); } this.cloudBlobClient = cloudBlobClient ?? GetStorageAccountFromConfigurationSetting().CreateCloudBlobClient(); this.webOperationContext = webOperationContext; this.requestValidator = requestValidator; this.userPrivilegesRepository = userPrivilegesRepository; }
private string GetAccessControlAllowOriginValue(WebOperationContext context) { var accessControlAllowOrigin = "*"; string allowedOrigins = AllowedOrigins; var providedOrigin = context.IncomingRequest.Headers.Get("Origin"); if (!string.IsNullOrWhiteSpace(providedOrigin)) { if (allowedOrigins.Contains(providedOrigin)) { accessControlAllowOrigin = providedOrigin; } } return accessControlAllowOrigin; }
public static void SetCaching(WebOperationContext context) { // set CacheControl header DateTime dt = DateTime.UtcNow.Date.AddHours(23).AddMinutes(59).AddSeconds(59); HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl; String cacheControlValue = String.Format("max-age={0}", 100); //context.OutgoingResponse.Headers.Add(cacheHeader, cacheControlValue); context.OutgoingResponse.Headers.Add("Expires", dt.ToUniversalTime().ToString("r")); // set cache validation context.OutgoingResponse.LastModified = DateTime.Now.ToUniversalTime();//.ToString("r"); String eTag = context.IncomingRequest.UriTemplateMatch.RequestUri.ToString(); context.OutgoingResponse.ETag = eTag; }
public WCFStandards () { // int Index = OperationContext.Current.RequestContext.RequestMessage.Headers.FindHeader ("WPMediaToken", ""); OperationContext OPC = OperationContext.Current; WebOperationContext WOC = new WebOperationContext (OPC); if (WebOperationContext.Current.IncomingRequest.Headers["WPMediaToken"] == null) throw new Exception ("WPMediaToken fehlt (Current)"); if (WOC.IncomingRequest.Headers ["WPMediaToken"] == null) throw new Exception("WPMediaToken fehlt (WOC)"); String WPMediaToken = WOC.IncomingRequest.Headers ["WPMediaToken"].ToString (); if (WPMediaToken != m_WPMediaToken) m_WPMediaToken = WPMediaToken; if (CheckWPMediaToken (m_WPMediaToken)) return; throw new Exception ("Kein gültiger WPMediaToken gefunden (Check war negativ)"); }
public override void CheckIdentity() { ClientTokenName = "token"; IsIdentityPass = false; if (OperationContext.Current == null) { throw new FaultException("WCF配置错误,OperationInterceptorClass 特性只能配置REST服务。请修改。"); } WebOperationContext context = new WebOperationContext(OperationContext.Current); var headers = context.IncomingRequest.Headers; if (!headers.IsNull()) { ClientToken = headers[ClientTokenName]; if (new BaseClientCheckFactory(ClientToken) .ClientIdentityCheck()) { IsIdentityPass = true; } } }
public SamplePushUserRegistrationService(HttpContextBase context, WebOperationContext webOperationContext, IPushUserEndpointsRepository pushUserEndpointsRepository, CloudQueueClient cloudQueueClient) { if ((context == null) && (HttpContext.Current == null)) { throw new ArgumentNullException("context", "Context cannot be null if not running on a Web context."); } if (pushUserEndpointsRepository == null) { throw new ArgumentNullException("pushUserEndpointsRepository", "PushUserEndpoints repository cannot be null."); } if ((cloudQueueClient == null) && (GetStorageAccountFromConfigurationSetting() == null)) { throw new ArgumentNullException("cloudQueueClient", "Cloud Queue Client cannot be null if no configuration is loaded."); } this.cloudQueueClient = cloudQueueClient ?? GetStorageAccountFromConfigurationSetting().CreateCloudQueueClient(); this.webOperationContext = webOperationContext; this.context = context; this.pushUserEndpointsRepository = pushUserEndpointsRepository; }
private static Guid GetGuidFromAuthHeader(WebOperationContext woc) { var request = woc.IncomingRequest; var headers = request.Headers; var authHeader = headers["Authorization"]; if (authHeader == null) { throw new JsonError(JsonResponseCode.WrongTokenType).GetException(); } var authHeaderPattern = new Regex("Token (.*)"); var match = authHeaderPattern.Match(authHeader); if (!match.Success) { throw new JsonError(JsonResponseCode.WrongTokenType).GetException(); } var guidStr = match.Groups[1].ToString(); Guid guid; if (!Guid.TryParse(guidStr, out guid)) { throw new JsonError(JsonResponseCode.WrongTokenType).GetException(); } return guid; }
/// <summary> /// REST 身份验证 /// </summary> /// <returns></returns> private bool IsIdentityPass() { string ClientTokenName = "token"; bool IsIdentityPass = false; if (OperationContext.Current == null) { throw new FaultException("WCF配置错误,OperationInterceptorClass 特性只能配置REST服务。请修改。"); } WebOperationContext context = new WebOperationContext(OperationContext.Current); var headers = context.IncomingRequest.Headers; if (headers != null) { string ClientToken = headers[ClientTokenName]; if (new BaseClientCheckFactory(ClientToken) .ClientIdentityCheck()) { IsIdentityPass = true; } } return IsIdentityPass; }
/// <summary> /// Logtypes: /// 1 = exception /// 2 = 404 error /// 3 = 403 error /// </summary> /// <param name="ex"></param> /// <param name="pageName"></param> /// <param name="logType"></param> /// <param name="context"> </param> public static void LogMessage(Exception ex, string pageName, int logType, WebOperationContext context = null) { var logRep = new LogRepository(); string clientInformation = context != null ? GetClientInformation(context.IncomingRequest) : "Not a webrequest"; if (ex is SqlException) { //TODO: Add log message to json/xml file //Create the Json file and save it with WriteToFile(); var jobject = new JObject( new JProperty("Exception", new JObject( new JProperty("CreatedDate", DateTime.Now), new JProperty("ClientInformation", clientInformation), new JProperty("LogType", logType), new JProperty("Exception", ex.ToString()), new JProperty("ExceptionLocation", pageName), new JProperty("IsActive", true) ) ) ); } else { var logEntity = new Log { ClientInformation = clientInformation, CreatedDate = DateTime.Now, Exception = ex.ToString(), ExceptionLocation = pageName, LogType = logType }; logRep.Insert(logEntity); } }
static HttpResponseMessageProperty GetResponseProperty(WebOperationContext currentContext, Message response) { HttpResponseMessageProperty responseProperty; if (currentContext != null) { responseProperty = currentContext.OutgoingResponse.MessageProperty; } else { responseProperty = new HttpResponseMessageProperty(); response.Properties.Add(HttpResponseMessageProperty.Name, responseProperty); } return responseProperty; }
public static void setupWebResponseNoCache(WebOperationContext context) { context.OutgoingResponse.Headers.Add("Expires", "-1"); context.OutgoingResponse.Headers.Add("Cache-Control", "no-cache, no-store"); }
public static System.ServiceModel.Channels.Message createJsonWebResponseNoCache(WebOperationContext context, string json) { setupWebResponseNoCache(context); return createJsonWebResponse(context, json); }
public static System.ServiceModel.Channels.Message createJsonWebResponseNoCache(WebOperationContext context, object data) { return createJsonWebResponseNoCache(context, JsonConvert.SerializeObject(data)); }
public static System.ServiceModel.Channels.Message createJsonWebResponse(WebOperationContext context, string json) { return context.CreateTextResponse(json, "application/json; charset=utf-8"); }
static Message CreateOwinResponse( WebOperationContext webResponse, string status, IDictionary<string, string> headers, BodyDelegate body) { //TODO: hardenning var statusCode = int.Parse(status.Substring(0, 3)); webResponse.OutgoingResponse.StatusCode = (HttpStatusCode) statusCode; webResponse.OutgoingResponse.StatusDescription = status.Substring(4); foreach (var header in Split(headers)) { webResponse.OutgoingResponse.Headers.Add(header.Key, header.Value); } string contentType; if (!headers.TryGetValue("Content-Type", out contentType)) contentType = "text/plain"; return webResponse.CreateStreamResponse( stream => { var done = new ManualResetEvent(false); body( (data, _) => { stream.Write(data.Array, data.Offset, data.Count); return false; }, ex => done.Set(), () => done.Set() ); done.WaitOne(); }, contentType); }
private Stream CreateTextResponse(WebOperationContext context, string text) { context.OutgoingResponse.ContentType = "text/plain; charset=utf-8"; return new MemoryStream(Encoding.UTF8.GetBytes(text)); }
public WebOperationContextWrapper(WebOperationContext context) { this.context = context; }
private void InnerChannel_Opened (object sender, EventArgs e) { if (WMB.WPMediaApplicationState.Instance.Properties.ContainsKey ("WPMediaToken") == false) { if (WMB.WPMediaApplicationState.Instance.Properties.ContainsKey ("UserName") == true) WMB.WPMediaApplicationState.Instance.Properties ["WPMediaToken"] = WMB.WPMediaApplicationState.Instance.Properties ["UserName"].ToString () + ";SecurityToken"; else { if (Application.Current.MainWindow != null) Application.Current.MainWindow.Close (); else Application.Current.Shutdown(); return; // throw new Exception ("WMB.WPMediaApplicationState.Instance.Properties.ContainsKey (\"UserName\") == false"); } } String WPMediaToken = WMB.WPMediaApplicationState.Instance.Properties ["WPMediaToken"].ToString(); if (WPMediaToken.IndexOf(";SecurityToken") < 2) throw new Exception("ClientSeitiger Fehler wegen WPMediaToken"); // because of problems in http Environment I skiped this checks //if (String.IsNullOrEmpty (Thread.CurrentPrincipal.Identity.Name)) // throw new Exception ("Thread.CurrentPrincipal.Identity.Name ist leer"); WebOperationContext WOC = new WebOperationContext (m_OPC); m_OPC.OutgoingMessageHeaders.Add (MessageHeader.CreateHeader ("WPMediaToken", "", WPMediaToken)); WOC.OutgoingRequest.Headers.Add ("WPMediaToken", WPMediaToken); WOC.OutgoingResponse.Headers.Add ("WPMediaToken", WPMediaToken); }
private static Message CreateMessage(WebOperationContext context, string text) { return context.CreateTextResponse(text, "text/plain", new UTF8Encoding(false)); }
/// <summary> /// Processes the request. /// </summary> /// <param name="structure">The structure.</param> /// <param name="agencyId">The agency id.</param> /// <param name="resourceId">The resource id.</param> /// <param name="version">The version.</param> /// <param name="ctx">The current <see cref="WebOperationContext"/>.</param> /// <returns> /// The <see cref="Message" />. /// </returns> /// <exception cref="System.Web.HttpBrowserCapabilitiesBase"></exception> /// <exception cref="WebFaultException{String}"> /// Cannot serve content type /// </exception> /// <exception cref="WebFaultException{String}">Cannot serve content type</exception> private Message ProcessRequest(string structure, string agencyId, string resourceId, string version, WebOperationContext ctx) { Match match = Regex.Match(resourceId, @"[A-Za-z0-9\-]+$", RegexOptions.IgnoreCase); if (!match.Success) { throw new WebFaultException(HttpStatusCode.BadRequest); } var defaultMediaType = StructureMediaType.GetFromEnum(StructureMediaEnumType.Structure).MediaTypeName; var requestAccept = ctx.IncomingRequest.Accept; Logger.Info("Got request Content type= " + requestAccept); IList<ContentType> acceptHeaderElements = ctx.IncomingRequest.GetAcceptHeaderElements(); Func<ContentType, bool> predicate = type => StructureMediaType.GetTypeFromName(type.MediaType) != null; var contentType = RestUtils.GetContentType(ctx, predicate, defaultMediaType); string requestedVersion = HeaderUtils.GetVersionFromAccept(acceptHeaderElements, contentType.MediaType); var selectedStructureMediaType = StructureMediaType.GetTypeFromName(contentType.MediaType); var selectedMediaTypeWithVersion = selectedStructureMediaType.GetMediaTypeVersion(requestedVersion); if (selectedMediaTypeWithVersion == null) { Logger.Error("Cannot serve content type: " + requestAccept); throw new WebFaultException<string>("Cannot serve content type: " + requestAccept, HttpStatusCode.NotAcceptable); } Logger.Debug("Select mediatype with version if required: " + selectedMediaTypeWithVersion); SdmxSchema schemaVersion = RestUtils.GetVersionFromMediaType(selectedMediaTypeWithVersion); var context = HttpContext.Current; var controller = this._controllerBuilder.BuildQueryStructureRest(schemaVersion, context.User as DataflowPrincipal); Logger.Info("Selected representation info for the controller: format =" + "TODO" + " , smdx_schema=" + version); IRestStructureQuery query = BuildRestQueryBean(structure, agencyId, resourceId, version, ctx.IncomingRequest.UriTemplateMatch.QueryParameters); var streamController = controller.ParseRequest(query); var charSetEncoding = RestUtils.GetCharSetEncoding(contentType); var responseContentType = RestUtils.GetContentType(contentType, selectedMediaTypeWithVersion); selectedMediaTypeWithVersion.CharSet = charSetEncoding.WebName; return ctx.CreateStreamResponse( stream => RestUtils.StreamXml(schemaVersion, stream, streamController, charSetEncoding), responseContentType); }
private bool HasNotSetResponseHeader(WebOperationContext context, string headerName) { return string.IsNullOrEmpty(context.OutgoingResponse.Headers.Get(headerName)); }
public HttpOperationContext(WebOperationContext webOperationContext) { _requestContext = new HttpRequestContext(webOperationContext.IncomingRequest); _responseContext = new HttpResponseContext(webOperationContext.OutgoingResponse); }