本文整理汇总了C#中OwinContext类的典型用法代码示例。如果您正苦于以下问题:C# OwinContext类的具体用法?C# OwinContext怎么用?C# OwinContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
OwinContext类属于命名空间,在下文中一共展示了OwinContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParseAsync
/// <summary>
/// Tries to find a secret on the environment that can be used for authentication
/// </summary>
/// <param name="environment">The environment.</param>
/// <returns>
/// A parsed secret
/// </returns>
public async Task<ParsedSecret> ParseAsync(IDictionary<string, object> environment)
{
Logger.Debug("Start parsing for secret in post body");
var context = new OwinContext(environment);
var body = await context.ReadRequestFormAsync();
if (body != null)
{
var id = body.Get("client_id");
var secret = body.Get("client_secret");
if (id.IsPresent() && secret.IsPresent())
{
var parsedSecret = new ParsedSecret
{
Id = id,
Credential = secret,
Type = Constants.ParsedSecretTypes.SharedSecret
};
return parsedSecret;
}
}
Logger.Debug("No secet in post body found");
return null;
}
示例2: Invoke
/// <summary>
/// Executes the given operation on a different thread, and waits for the result.
/// </summary>
/// <param name="env">The environment.</param>
/// <returns>
/// A Task.
/// </returns>
public async Task Invoke(IDictionary<string, object> env)
{
var context = new OwinContext(env);
if (context.Request.Uri.LocalPath.ToLower().StartsWith("/post"))
{
var content = Uri.UnescapeDataString(context.Request.Uri.Query.Substring(1));
var msg = (IMessage)await this.serializationService.JsonDeserializeAsync<PostMessage>(content).PreserveThreadContext();
var msgResponse = await this.messageProcessor.ProcessAsync(msg).PreserveThreadContext();
var msgJson = await this.serializationService.JsonSerializeAsync(msgResponse).PreserveThreadContext();
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(msgJson);
return;
}
try
{
await this.next(env);
}
catch (OperationCanceledException)
{
// be silent on cancelled.
}
}
示例3: MaxUrlLength
/// <summary>
/// Limits the length of the URL.
/// </summary>
/// <param name="getMaxUrlLength">A delegate to get the maximum URL length.</param>
/// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
/// <returns>An OWIN middleware delegate.</returns>
/// <exception cref="System.ArgumentNullException">getMaxUrlLength</exception>
public static MidFunc MaxUrlLength(Func<RequestContext, int> getMaxUrlLength, string loggerName = null)
{
getMaxUrlLength.MustNotNull("getMaxUrlLength");
loggerName = string.IsNullOrWhiteSpace(loggerName)
? "LimitsMiddleware.MaxUrlLength"
: loggerName;
var logger = LogProvider.GetLogger(loggerName);
return
next =>
env =>
{
var context = new OwinContext(env);
int maxUrlLength = getMaxUrlLength(new RequestContext(context.Request));
string unescapedUri = Uri.UnescapeDataString(context.Request.Uri.AbsoluteUri);
logger.Debug("Checking request url length.");
if (unescapedUri.Length > maxUrlLength)
{
logger.Info(
"Url \"{0}\"(Length: {2}) exceeds allowed length of {1}. Request rejected.".FormatWith(
unescapedUri,
maxUrlLength,
unescapedUri.Length));
context.Response.StatusCode = 414;
context.Response.ReasonPhrase = "Request-URI Too Large";
context.Response.Write(context.Response.ReasonPhrase);
return Task.FromResult(0);
}
logger.Debug("Check passed. Request forwarded.");
return next(env);
};
}
示例4: Invoke
public async Task Invoke(IDictionary<string, object> env)
{
var context = new OwinContext(env);
if (context.Request.Uri.Scheme != Uri.UriSchemeHttps)
{
context.Response.StatusCode = 403;
context.Response.ReasonPhrase = "SSL is required.";
return;
}
if (_options.RequireClientCertificate)
{
var cert = context.Get<X509Certificate2>("ssl.ClientCertificate");
if (cert == null)
{
context.Response.StatusCode = 403;
context.Response.ReasonPhrase = "SSL client certificate is required.";
return;
}
}
await _next(env);
}
示例5: EmptyOwinEnvironment
public async void EmptyOwinEnvironment()
{
var context = new OwinContext();
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
示例6: Invoke
public async Task Invoke(IDictionary<string, object> env)
{
var context = new OwinContext(env);
await context.Response.WriteAsync("Middleware 2 ");
await this.next(env);
await context.Response.WriteAsync("middleware 2 way back: ");
}
示例7: ExpectedKeysAreAvailable
public void ExpectedKeysAreAvailable()
{
var handler = new OwinClientHandler(env =>
{
IOwinContext context = new OwinContext(env);
Assert.Equal("1.0", context.Get<string>("owin.Version"));
Assert.NotNull(context.Get<CancellationToken>("owin.CallCancelled"));
Assert.Equal("HTTP/1.1", context.Request.Protocol);
Assert.Equal("GET", context.Request.Method);
Assert.Equal("https", context.Request.Scheme);
Assert.Equal(string.Empty, context.Get<string>("owin.RequestPathBase"));
Assert.Equal("/A/Path/and/file.txt", context.Get<string>("owin.RequestPath"));
Assert.Equal("and=query", context.Get<string>("owin.RequestQueryString"));
Assert.NotNull(context.Request.Body);
Assert.NotNull(context.Get<IDictionary<string, string[]>>("owin.RequestHeaders"));
Assert.NotNull(context.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"));
Assert.NotNull(context.Response.Body);
Assert.Equal(200, context.Get<int>("owin.ResponseStatusCode"));
Assert.Null(context.Get<string>("owin.ResponseReasonPhrase"));
Assert.Equal("example.com", context.Request.Headers.Get("Host"));
return Task.FromResult(0);
});
var httpClient = new HttpClient(handler);
httpClient.GetAsync("https://example.com/A/Path/and/file.txt?and=query").Wait();
}
示例8: Invoke
/// <summary>
/// Invokes the middleware.
/// </summary>
/// <param name="environment">The OWIN environment.</param>
/// <returns>Task.</returns>
/// <exception cref="InvalidOperationException">No SelfTester set on the SelfTestMiddlewareOptions provided.</exception>
public async Task Invoke(IDictionary<string, object> environment)
{
if (_options.SelfTester == null)
{
throw new InvalidOperationException("No SelfTester set on the SelfTestMiddlewareOptions provided.");
}
var context = new OwinContext(environment);
if (!IsEndPointUrl(context))
{
await _next(environment);
}
else {
if (!await CheckToken(context))
{
return;
}
context.Response.ContentType = "application/json";
ISelfTestResult result = await _options.SelfTester.RunTests();
string output = JsonConvert.SerializeObject(result, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
context.Response.StatusCode = (int)HttpStatusCode.OK;
await context.Response.WriteAsync(output);
// No call to _next since this is a terminal middleware
}
}
示例9: ShouldSkipAuthOnWrongAuthScheme
public void ShouldSkipAuthOnWrongAuthScheme()
{
var builder = new AppBuilderFactory().Create();
var context = new OwinContext();
OwinRequest request = (OwinRequest)context.Request;
request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
request.Method = "get";
request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
request.SetHeader("Authorization", new string[] { "Basic " });
var response = context.Response;
var middleware = new HawkAuthenticationMiddleware(
new AppFuncTransition((env) =>
{
response.StatusCode = 200;
return Task.FromResult<object>(null);
}),
builder,
new HawkAuthenticationOptions
{
Credentials = GetCredential
}
);
middleware.Invoke(context);
Assert.IsNotNull(response);
Assert.AreEqual(200, response.StatusCode);
}
示例10: SignOut
public static void SignOut(this NancyModule module)
{
var env = module.Context.GetOwinEnvironment();
var owinContext = new OwinContext(env);
owinContext.Authentication.SignOut(TheBenchConstants.TheBenchAuthType);
}
示例11: Invoke
public async Task Invoke(IDictionary<string, object> env)
{
var context = new OwinContext(env);
context.Authentication.User = this.CreateUser();
await this._next(env);
}
示例12: Authorize
public bool Authorize(IDictionary<string, object> owinEnvironment)
{
var context = new OwinContext(owinEnvironment);
var principal = context.Authentication.User;
var isAuthorized = IsAuthorized(_permissionService, principal);
return isAuthorized;
}
示例13: UseHangfireServer
public static IAppBuilder UseHangfireServer(
[NotNull] this IAppBuilder builder,
[NotNull] BackgroundJobServerOptions options,
[NotNull] JobStorage storage)
{
if (builder == null) throw new ArgumentNullException("builder");
if (options == null) throw new ArgumentNullException("options");
if (storage == null) throw new ArgumentNullException("storage");
var server = new BackgroundJobServer(options, storage);
Servers.Add(server);
var context = new OwinContext(builder.Properties);
var token = context.Get<CancellationToken>("host.OnAppDisposing");
if (token == default(CancellationToken))
{
// https://github.com/owin/owin/issues/27
token = context.Get<CancellationToken>("server.OnDispose");
}
if (token == default(CancellationToken))
{
throw new InvalidOperationException("Current OWIN environment does not contain an instance of the `CancellationToken` class under `host.OnAppDisposing` key.");
}
token.Register(server.Dispose);
return builder;
}
示例14: BuildHtmlTable
private static string BuildHtmlTable(OwinContext context) {
var builder = new StringBuilder();
builder.Append("<table border='1'><tr><th>Key</th><th>Value</th></tr>");
List<string> keys = context.Environment.Keys.OrderBy(key => key)
.ToList();
foreach (var key in keys) {
var value = context.Environment[key];
var valueDictionary = value as IDictionary<string, string[]>;
if (valueDictionary == null) {
builder.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", key, value);
}
else {
builder.AppendFormat("<tr><td>{0}</td><td>count ={1}</td></tr>", key, valueDictionary.Count);
if (valueDictionary.Count == 0) {
continue;
}
builder.Append("<tr><td> </td><td><table border='1'><tr><th>Key</th><th>Value</th></tr>");
List<string> valueKeys = valueDictionary.Keys.OrderBy(key2 => key2)
.ToList();
foreach (var valueKey in valueKeys) {
builder.AppendFormat("<tr><td>{0}</td><td>{1}</td><tr>", valueKey, string.Join("<br />", valueDictionary[valueKey]));
}
builder.Append("</table></td></tr>");
}
}
builder.Append("</table>");
return builder.ToString();
}
示例15: Invoke
public async Task Invoke(IDictionary<string, object> env)
{
var context = new OwinContext(env);
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(this.options.Greeting);
await this.next(env);
}