本文整理汇总了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;
}
}
示例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());
}
示例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);
}
示例4: ActivateCurrencyPair
private Task ActivateCurrencyPair(IRequestContext context, IMessage message)
{
var payload =
JsonConvert.DeserializeObject<ActivateCurrencyPairRequestDto>(Encoding.UTF8.GetString(message.Payload));
return _service.ActivateCurrencyPair(context, payload);
}
示例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;
}
示例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);
}
}
}
示例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("<", "<").Replace(">", ">");
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);
}
示例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();
}
}
}
}
示例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);
}
}
示例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());
}
}
示例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);
}
}
示例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);
}
示例13: WatchController
public WatchController(IWatchService watchService, IImageService imageService, IOrderService orderService, IRequestContext requestContext)
{
_watchService = watchService;
_imageService = imageService;
_orderService = orderService;
_requestContext = requestContext;
}
示例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);
}
示例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);
}