当前位置: 首页>>代码示例>>C#>>正文


C# IRequestContext类代码示例

本文整理汇总了C#中IRequestContext的典型用法代码示例。如果您正苦于以下问题:C# IRequestContext类的具体用法?C# IRequestContext怎么用?C# IRequestContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


IRequestContext类属于命名空间,在下文中一共展示了IRequestContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendHeaders

        protected virtual void SendHeaders(IRequestContext context)
        {
            // Location: header should be absolute per RFC 2616 para 14.30. Enforce this.

            string location;
            if (Headers.TryGetValue("Location", out location)) {
                Uri u;
                if (!Uri.TryCreate(location, UriKind.Absolute, out u)) {
                    var parts = location.Split(new char[] { '?' }, 2);
                    if (parts.Length == 2) {
                        u = context.Request.GetAbsoluteUrl(new VirtualPath(parts[0]));
                        Headers["Location"] = u.ToString() + "?" + parts[1];
                    }
                    else {
                        u = context.Request.GetAbsoluteUrl(new VirtualPath(location));
                        Headers["Location"] = u.ToString();
                    }
                }
            }

            context.Response.Status = Status;
            foreach (var key in Headers.Keys) {
                context.Response.AddHeader(key, Headers[key]);
            }

            if (MimeType != null) {
                context.Response.Headers.MimeType = MimeType;
            }

            if (Encoding != null) {
                context.Response.Headers.Encoding = Encoding;
            }
        }
开发者ID:jammycakes,项目名称:dolstagis.web,代码行数:33,代码来源:ResultBase.cs

示例2: ProcessTextAsync

        public Task<string> ProcessTextAsync(string text, IRequestContext context, CancellationToken cancellationToken)
        {
            var words = text.Split(' ');

            var correctTextBuilder = new StringBuilder();

            foreach (var word in words)
            {
                decimal number = 0;
                string correctedWord = null;

                if (!decimal.TryParse(word, out number))
                {
                    if (word.Length > 1)
                    {
                        correctedWord = _spellCorrect.Correct(word);
                    }
                }

                if (correctedWord != null)
                {
                    correctTextBuilder.AppendFormat("{0} ", correctedWord);
                }
                else
                {
                    correctTextBuilder.AppendFormat("{0} ", word);
                }
            }

            return Task.FromResult(correctTextBuilder.ToString().Trim());
        }
开发者ID:leonmeijer,项目名称:textc-csharp,代码行数:31,代码来源:SpellCorrectPreProcessor.cs

示例3: GetTradesStream

        private async Task GetTradesStream(IRequestContext context, IMessage message)
        {
            Log.Debug("Received GetTradesStream from {username}", context.UserSession.Username ?? "<UNKNOWN USER>");
            var replyTo = message.ReplyTo;

            var endPoint = await _broker.GetPrivateEndPoint<TradesDto>(replyTo);

            _subscription = _service.GetTradesStream()
                .Select(x =>
                {
                    if (x.IsStateOfTheWorld && x.Trades.Count > MaxSotwTrades)
                    {
                        return new TradesDto(new List<TradeDto>(x.Trades.Skip(x.Trades.Count - MaxSotwTrades)), true, false);
                    }
                    return x;
                })
                .Do(o =>
                {
                    Log.Debug(
                        $"Sending trades update to {replyTo}. Count: {o.Trades.Count}. IsStateOfTheWorld: {o.IsStateOfTheWorld}. IsStale: {o.IsStale}");
                })
                .TakeUntil(endPoint.TerminationSignal)
                .Finally(() => Log.Debug("Tidying up subscription from {replyTo}.", replyTo))
                .Subscribe(endPoint);
        }
开发者ID:AdaptiveConsulting,项目名称:ReactiveTraderCloud,代码行数:25,代码来源:BlotterServiceHost.cs

示例4: ActivateCurrencyPair

        private Task ActivateCurrencyPair(IRequestContext context, IMessage message)
        {
            var payload =
                JsonConvert.DeserializeObject<ActivateCurrencyPairRequestDto>(Encoding.UTF8.GetString(message.Payload));

            return _service.ActivateCurrencyPair(context, payload);
        }
开发者ID:AdaptiveConsulting,项目名称:ReactiveTraderCloud,代码行数:7,代码来源:ReferenceWriteServiceHost.cs

示例5: ProcessEvent

        /// <summary>
        /// This is the one where all the magic happens.
        /// </summary>
        /// <returns>The outcome of the policy Execution as per ISubscriber's contract</returns>
        /// <param name="requestContext">TFS Request Context</param>
        /// <param name="notification">The <paramref name="notification"/> containing the WorkItemChangedEvent</param>
        public ProcessingResult ProcessEvent(IRequestContext requestContext, INotification notification)
        {
            var result = new ProcessingResult();

            Policy[] policies = this.FilterPolicies(this.settings.Policies, requestContext, notification).ToArray();

            if (policies.Any())
            {
                IWorkItem workItem = this.store.GetWorkItem(notification.WorkItemId);

                foreach (var policy in policies)
                {
                    this.logger.ApplyingPolicy(policy.Name);
                    this.ApplyRules(workItem, policy.Rules);
                }

                this.SaveChangedWorkItems();
                result.StatusCode = 0;
                result.StatusMessage = "Success";
            }
            else
            {
                result.StatusCode = 1;
                result.StatusMessage = "No operation";
            }

            return result;
        }
开发者ID:DEllingsworth,项目名称:tfsaggregator,代码行数:34,代码来源:EventProcessor.cs

示例6: SendBodyAsync

 protected override async Task SendBodyAsync(IRequestContext context)
 {
     if (Xslt != null) {
         if (Model is XDocument)
             await TransformAsync(context, ((XDocument)Model).CreateNavigator());
         else if (Model is IXPathNavigable)
             await TransformAsync(context, ((IXPathNavigable)Model));
         else {
             var ser = Serializer ?? new XmlSerializer(Model.GetType());
             var doc = new XDocument();
             using (var writer = doc.CreateWriter())
                 ser.Serialize(writer, Model);
             await TransformAsync(context, doc.CreateNavigator());
         }
     }
     else {
         using (var writer = context.Response.GetStreamWriter()) {
             if (Model is XDocument)
                 ((XDocument)Model).Save(writer);
             else if (Model is XmlDocument)
                 ((XmlDocument)Model).Save(writer);
             else if (Model is IXPathNavigable)
                 using (var xWriter = new XmlTextWriter(writer))
                     ((IXPathNavigable)Model).CreateNavigator().WriteSubtree(xWriter);
             else
                 (Serializer ?? new XmlSerializer(Model.GetType()))
                     .Serialize(writer, Model);
         }
     }
 }
开发者ID:jammycakes,项目名称:dolstagis.web,代码行数:30,代码来源:XmlResult.cs

示例7: SerializeToStream

        public void SerializeToStream(IRequestContext requestContext, object dto, IHttpResponse httpRes)
        {
            var httpReq = requestContext.Get<IHttpRequest>();
            if (AppHost.ViewEngines.Any(x => x.ProcessRequest(httpReq, httpRes, dto))) return;

            if (requestContext.ResponseContentType != ContentType.Html
                && httpReq.ResponseContentType != ContentType.JsonReport) return;

            // Serialize then escape any potential script tags to avoid XSS when displaying as HTML
            var json = JsonDataContractSerializer.Instance.SerializeToString(dto) ?? "null";
            json = json.Replace("<", "&lt;").Replace(">", "&gt;");

            var url = httpReq.AbsoluteUri
                .Replace("format=html", "")
                .Replace("format=shtm", "")
                .TrimEnd('?', '&');

            url += url.Contains("?") ? "&" : "?";

            var now = DateTime.UtcNow;
            var requestName = httpReq.OperationName ?? dto.GetType().Name;

            string html = GetHtmlTemplate()
                .Replace("${Dto}", json)
                .Replace("${Title}", string.Format(TitleFormat, requestName, now))
                .Replace("${MvcIncludes}", MiniProfiler.Profiler.RenderIncludes().ToString())
                .Replace("${Header}", string.Format(HtmlTitleFormat, requestName, now))
                .Replace("${ServiceUrl}", url);

            var utf8Bytes = html.ToUtf8Bytes();
            httpRes.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
        }
开发者ID:rajeshpillai,项目名称:ServiceStack,代码行数:32,代码来源:HtmlFormat.cs

示例8: SerializeToStream

        public static void SerializeToStream(IRequestContext context, object response, Stream stream)
        {
            var drinkCardResponse = response as DrinkCardResponse;

            if (drinkCardResponse != null)
            {
                using (var writer = new StreamWriter(stream))
                {
                    foreach (var drinkCard in drinkCardResponse.Cards)
                    {
                        writer.WriteLine("Id: {0}", drinkCard.Id);
                        writer.WriteLine("Name: {0}", drinkCard.Name);
                        writer.WriteLine("CardType: {0}", drinkCard.CardType);

                        writer.WriteLine("Drinks:");
                        foreach (var drink in drinkCard.Drinks)
                        {
                            writer.WriteLine("\t{0}", drink.Name);
                        }

                        writer.WriteLine();
                    }
                }
            }
        }
开发者ID:cyberzed,项目名称:NDC2012_NoMoreMagic,代码行数:25,代码来源:DrinkCardFormat.cs

示例9: AssertNoFault

 /// <summary>
 /// Convenience method to confirm that no Exception was caught.
 /// </summary>
 /// <param name="context">Context under test</param>
 /// 
 public void AssertNoFault(IRequestContext context)
 {
     if (context.HasFault)
     {
         FaultText(context.Fault);
     }
 }
开发者ID:benouarred,项目名称:struts-archive,代码行数:12,代码来源:BaseNexusTest.cs

示例10: AssertNominal

 /// <summary>
 /// Convenience method to confirm 
 /// that there are no alerts or fault.
 /// </summary>
 /// <param name="context">Context under test</param>
 /// 
 public void AssertNominal(IRequestContext context)
 {
     AssertNoFault(context);
     bool hasAlerts = context.HasAlerts;
     if (hasAlerts)
     {
         // TODO: Use new TextOnly method here.
         StringBuilder outer = new StringBuilder();
         IDictionary store = context.Alerts;
         ICollection keys = store.Keys;
         foreach (string key in keys)
         {
             StringBuilder inner = new StringBuilder();
             inner.Append(key);
             inner.Append(": ");
             IList messages = store[key] as IList;
             foreach (string message in messages)
             {
                 inner.Append(message);
                 inner.Append(";");
             }
             outer.Append(inner.ToString());
             outer.Append("/n");
         }
         Assert.Fail(outer.ToString());
     }
 }
开发者ID:benouarred,项目名称:struts-archive,代码行数:33,代码来源:BaseNexusTest.cs

示例11: HandleRequest

        public override void HandleRequest(IRequestContext ctx)
        {
            string v;
            if (!ctx.UrlVariables.TryGetValue(RcParam, out v))
                v = ctx.QueryString[RcParam];
            if (v == null || v.Length == 0)
                v = "index.htm";
            ctx.ResponseContentType = MimeTypes.GetMimeTypeForExtension(Path.GetExtension(v));

            string pth = Path.GetFullPath(Path.Combine(BaseDirectory, v));
            if (Path.GetDirectoryName(pth).Length < BaseDirectory.Length)
            {
                log.Warn("Trying to get content above the root dir: {0}", pth);
                throw new NotFoundException();
            }
            if (!File.Exists(pth)) throw new NotFoundException();

            FileInfo fi = new FileInfo(pth);
            ctx.ResponseContentLength = (int) fi.Length;

            using (Stream stm = fi.OpenRead())
            {
                CopyStream(stm, ctx.OutputStream);
            }
        }
开发者ID:BrettBailey,项目名称:nginn-messagebus,代码行数:25,代码来源:FSDirectoryServlet.cs

示例12: AddReminderAsync

 public Task<Reminder> AddReminderAsync(string message, string when, IRequestContext context)
 {            
     var reminder = new Reminder(message, when);
     _reminders.Add(reminder);
     context.Clear();
     return Task.FromResult(reminder);            
 }
开发者ID:leonmeijer,项目名称:textc-csharp,代码行数:7,代码来源:Calendar.cs

示例13: WatchController

 public WatchController(IWatchService watchService, IImageService imageService, IOrderService orderService, IRequestContext requestContext)
 {
     _watchService = watchService;
     _imageService = imageService;
     _orderService = orderService;
     _requestContext = requestContext;
 }
开发者ID:TregubovAndrew,项目名称:MvcWatchStore,代码行数:7,代码来源:WatchController.cs

示例14: GetUser

 public Task<IUser> GetUser(IRequestContext context)
 {
     if (context.Session == null) return null;
     object result;
     return Task.FromResult<IUser>
         (context.Session.Items.TryGetValue(SessionKey, out result) ? result as IUser : null);
 }
开发者ID:jammycakes,项目名称:dolstagis.web,代码行数:7,代码来源:SessionAuthenticator.cs

示例15: Log

        public void Log(IRequestContext requestContext, object requestDto)
        {
            var httpReq = requestContext.Get<IHttpRequest>();
            var entry = new RequestLogEntry {
                Id = Interlocked.Increment(ref requestId),
                DateTime = DateTime.UtcNow,
                HttpMethod = httpReq.HttpMethod,
                AbsoluteUri = httpReq.AbsoluteUri,
                IpAddress = requestContext.IpAddress,
                PathInfo = httpReq.PathInfo,
                Referer = httpReq.Headers[HttpHeaders.Referer],
                Headers = httpReq.Headers.ToDictionary(),
                UserAuthId = httpReq.GetItemOrCookie(HttpHeaders.XUserAuthId),
                SessionId = httpReq.GetSessionId(),
                Items = httpReq.Items,
            };

            if (HideRequestBodyForRequestDtoTypes != null
                && requestDto != null
                && !HideRequestBodyForRequestDtoTypes.Contains(requestDto.GetType()))
            {
                entry.RequestDto = requestDto;
                entry.FormData = httpReq.FormData.ToDictionary();
            }

            logEntries.Enqueue(entry);

            RequestLogEntry dummy;
            if (logEntries.Count > capacity)
                logEntries.TryDequeue(out dummy);
        }
开发者ID:mnishihan,项目名称:ServiceStack,代码行数:31,代码来源:InMemoryRollingRequestLogger.cs


注:本文中的IRequestContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。