本文整理汇总了C#中OwinContext类的典型用法代码示例。如果您正苦于以下问题:C# OwinContext类的具体用法?C# OwinContext怎么用?C# OwinContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
OwinContext类属于命名空间,在下文中一共展示了OwinContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
开发者ID:nheijminkccv,项目名称:IdentityServer3,代码行数:35,代码来源:PostBodySecretParser.cs
示例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.
}
}
开发者ID:raimu,项目名称:kephas,代码行数:35,代码来源:ChatAppApiMiddleware.cs
示例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);
};
}
开发者ID:yonglehou,项目名称:LimitsMiddleware,代码行数:41,代码来源:Limits.MaxUrlLength.cs
示例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);
}
开发者ID:RyanLiu99,项目名称:Thinktecture.IdentityModel,代码行数:26,代码来源:RequireSslMiddleware.cs
示例5: EmptyOwinEnvironment
public async void EmptyOwinEnvironment()
{
var context = new OwinContext();
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
开发者ID:284247028,项目名称:IdentityServer3,代码行数:7,代码来源:BasicAuthenticationCredentialParsing.cs
示例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: ");
}
开发者ID:kandaraj,项目名称:katana-owin-examples,代码行数:7,代码来源:Startup.cs
示例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();
}
开发者ID:Kstal,项目名称:Microsoft.Owin,代码行数:28,代码来源:OwinClientHandlerTests.cs
示例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
}
}
开发者ID:NetChris,项目名称:NetChris.Web.SelfTest,代码行数:41,代码来源:SelfTestMiddleware.cs
示例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);
}
开发者ID:linkypi,项目名称:hawknet,代码行数:31,代码来源:HawkAuthenticationHandlerFixture.cs
示例10: SignOut
public static void SignOut(this NancyModule module)
{
var env = module.Context.GetOwinEnvironment();
var owinContext = new OwinContext(env);
owinContext.Authentication.SignOut(TheBenchConstants.TheBenchAuthType);
}
开发者ID:CumpsD,项目名称:CC.TheBench,代码行数:7,代码来源:SignOutExtension.cs
示例11: Invoke
public async Task Invoke(IDictionary<string, object> env)
{
var context = new OwinContext(env);
context.Authentication.User = this.CreateUser();
await this._next(env);
}
开发者ID:shanekm,项目名称:WebApiAuthentication,代码行数:7,代码来源:AuthenticationSimulator.cs
示例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;
}
开发者ID:rajendra1809,项目名称:VirtoCommerce,代码行数:7,代码来源:PermissionBasedAuthorizationFilter.cs
示例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;
}
开发者ID:djrineh,项目名称:Hangfire,代码行数:29,代码来源:AppBuilderExtensions.cs
示例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();
}
开发者ID:xamele0n,项目名称:Simple.Owin,代码行数:28,代码来源:DumpEnvironmentMiddleware.cs
示例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);
}
开发者ID:mkandroid15,项目名称:Samples,代码行数:7,代码来源:Program.cs
示例16: MaxBandwidthPerRequest
/// <summary>
/// Limits the bandwith used by the subsequent stages in the owin pipeline.
/// </summary>
/// <param name="getMaxBytesPerSecond">
/// A delegate to retrieve the maximum number of bytes per second to be transferred.
/// Allows you to supply different values at runtime. Use 0 or a negative number to specify infinite bandwidth.
/// </param>
/// <returns>An OWIN middleware delegate.</returns>
/// <exception cref="System.ArgumentNullException">getMaxBytesPerSecond</exception>
public static MidFunc MaxBandwidthPerRequest(Func<RequestContext, int> getMaxBytesPerSecond)
{
getMaxBytesPerSecond.MustNotNull("getMaxBytesPerSecond");
return
next =>
async env =>
{
var context = new OwinContext(env);
Stream requestBodyStream = context.Request.Body ?? Stream.Null;
Stream responseBodyStream = context.Response.Body;
var limitsRequestContext = new RequestContext(context.Request);
var requestTokenBucket = new FixedTokenBucket(
() => getMaxBytesPerSecond(limitsRequestContext));
var responseTokenBucket = new FixedTokenBucket(
() => getMaxBytesPerSecond(limitsRequestContext));
using (requestTokenBucket.RegisterRequest())
using (responseTokenBucket.RegisterRequest())
{
context.Request.Body = new ThrottledStream(requestBodyStream, requestTokenBucket);
context.Response.Body = new ThrottledStream(responseBodyStream, responseTokenBucket);
//TODO consider SendFile interception
await next(env).ConfigureAwait(false);
}
};
}
开发者ID:yonglehou,项目名称:LimitsMiddleware,代码行数:40,代码来源:Limits.MaxBandwidthPerRequest.cs
示例17: Invoke
public Task Invoke(EnvDict env)
{
var ctx = new OwinContext(env);
var v = ctx.Request.Headers.Get(this.header);
RouteParams.Set(env, this.paramKey, v);
return next.Invoke(env);
}
开发者ID:Xamarui,项目名称:OwinUtils,代码行数:7,代码来源:RouteHeader.cs
示例18: ShouldFailOnMissingAuthAttribute
public void ShouldFailOnMissingAuthAttribute()
{
var logger = new Logger();
var builder = new AppBuilderFactory().Create();
builder.SetLoggerFactory(new LoggerFactory(logger));
var context = new OwinContext();
var 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[] { "Hawk " +
"ts = \"1353788437\", mac = \"/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\""});
var response = (OwinResponse)context.Response;
response.StatusCode = 401;
var middleware = new HawkAuthenticationMiddleware(
new AppFuncTransition((env) =>
{
response.StatusCode = 401;
return Task.FromResult<object>(null);
}),
builder,
new HawkAuthenticationOptions
{
Credentials = GetCredential
}
);
middleware.Invoke(context);
Assert.AreEqual(401, response.StatusCode);
Assert.AreEqual("Missing attributes", logger.Messages[0]);
}
开发者ID:linkypi,项目名称:hawknet,代码行数:34,代码来源:HawkAuthenticationHandlerFixture.cs
示例19: Configuration
public void Configuration(IAppBuilder app)
{
// Loads the config from our App.config
XmlConfigurator.Configure();
// MassTransit to use Log4Net
Log4NetLogger.Use();
var container = IocConfig.RegisterDependencies();
// Sets the Mvc resolver
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// Sets Mvc Owin resolver as well
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
// Starts Mass Transit Service bus, and registers stopping of bus on app dispose
var bus = container.Resolve<IBusControl>();
var busHandle = bus.StartAsync().Result;
if (app.Properties.ContainsKey("host.OnAppDisposing"))
{
var context = new OwinContext(app.Properties);
var token = context.Get<CancellationToken>("host.OnAppDisposing");
if (token != CancellationToken.None)
{
token.Register(() => busHandle.Stop(TimeSpan.FromSeconds(30)));
}
}
}
开发者ID:maldworth,项目名称:tutorial-masstransit-send-vs-publish,代码行数:31,代码来源:Startup.cs
示例20: HomeModule
public HomeModule()
{
Get["/"] = x =>
{
var owinContext = new OwinContext(Context.GetOwinEnvironment());
var inputModel = this.Bind<HomeBindingModel>();
var model = new HomeViewModel
{
Text = string.Format("Input from Query String: {0} - {1}", inputModel.Input1, inputModel.Input2),
Method = owinContext.Request.Method
};
return View["home", model];
};
Post["/"] = x =>
{
var owinContext = new OwinContext(Context.GetOwinEnvironment());
var inputModel = this.Bind<HomeBindingModel>();
var model = new HomeViewModel
{
Text = string.Format("Input from Form Post: {0} - {1}", inputModel.Input1, inputModel.Input2),
Method = owinContext.Request.Method
};
return View["home", model];
};
}
开发者ID:amaitland,项目名称:CefSharp.Owin,代码行数:30,代码来源:HomeModule.cs
注:本文中的OwinContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论