DotNet 学习笔记 OWIN
Open Web Interface for .NET (OWIN) -------------------------------------------------------------------------
Running OWIN middleware in the ASP.NET pipeline
"dependencies": {
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.AspNetCore.Owin": "1.0.0"
}, public Task OwinHello(IDictionary<string, object> environment)
{
string responseText = "Hello World via OWIN";
byte[] responseBytes = Encoding.UTF8.GetBytes(responseText); // OWIN Environment Keys: http://owin.org/spec/spec/owin-1.0.0.html
var responseStream = (Stream)environment["owin.ResponseBody"];
var responseHeaders = (IDictionary<string, string[]>)environment["owin.ResponseHeaders"]; responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
responseHeaders["Content-Type"] = new string[] { "text/plain" }; return responseStream.WriteAsync(responseBytes, , responseBytes.Length);
} public void Configure(IApplicationBuilder app)
{
app.UseOwin(pipeline =>
{
pipeline(next => OwinHello);
});
}
app.UseOwin(pipeline =>
{
pipeline(next =>
{
// do something before
return OwinHello;
// do something after
});
});
-------------------------------------------------------------------------------------------------
Using ASP.NET Hosting on an OWIN-based server using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Owin;
using Microsoft.Extensions.Options;
using Nowin; namespace NowinSample
{
public class NowinServer : IServer
{
private INowinServer _nowinServer;
private ServerBuilder _builder; public IFeatureCollection Features { get; } = new FeatureCollection(); public NowinServer(IOptions<ServerBuilder> options)
{
Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());
_builder = options.Value;
} public void Start<TContext>(IHttpApplication<TContext> application)
{
// Note that this example does not take into account of Nowin's "server.OnSendingHeaders" callback.
// Ideally we should ensure this method is fired before disposing the context.
Func<IDictionary<string, object>, Task> appFunc = async env =>
{
// The reason for 2 level of wrapping is because the OwinFeatureCollection isn't mutable
// so features can't be added
var features = new FeatureCollection(new OwinFeatureCollection(env)); var context = application.CreateContext(features);
try
{
await application.ProcessRequestAsync(context);
}
catch (Exception ex)
{
application.DisposeContext(context, ex);
throw;
} application.DisposeContext(context, null);
}; // Add the web socket adapter so we can turn OWIN websockets into ASP.NET Core compatible web sockets.
// The calling pattern is a bit different
appFunc = OwinWebSocketAcceptAdapter.AdaptWebSockets(appFunc); // Get the server addresses
var address = Features.Get<IServerAddressesFeature>().Addresses.First(); var uri = new Uri(address);
var port = uri.Port;
IPAddress ip;
if (!IPAddress.TryParse(uri.Host, out ip))
{
ip = IPAddress.Loopback;
} _nowinServer = _builder.SetAddress(ip)
.SetPort(port)
.SetOwinApp(appFunc)
.Build();
_nowinServer.Start();
} public void Dispose()
{
_nowinServer?.Dispose();
}
}
} using System;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.Extensions.DependencyInjection;
using Nowin;
using NowinSample; namespace Microsoft.AspNetCore.Hosting
{
public static class NowinWebHostBuilderExtensions
{
public static IWebHostBuilder UseNowin(this IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddSingleton<IServer, NowinServer>();
});
} public static IWebHostBuilder UseNowin(this IWebHostBuilder builder, Action<ServerBuilder> configure)
{
builder.ConfigureServices(services =>
{
services.Configure(configure);
});
return builder.UseNowin();
}
}
} using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting; namespace NowinSample
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseNowin()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build(); host.Run();
}
}
} ------------------------------------------------------------------------------
Run ASP.NET Core on an OWIN-based server and use its WebSockets support
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await EchoWebSocket(webSocket);
}
else
{
await next();
}
}); app.Run(context =>
{
return context.Response.WriteAsync("Hello World");
});
} private async Task EchoWebSocket(WebSocket webSocket)
{
byte[] buffer = new byte[];
WebSocketReceiveResult received = await webSocket.ReceiveAsync(
new ArraySegment<byte>(buffer), CancellationToken.None); while (!webSocket.CloseStatus.HasValue)
{
// Echo anything we receive
await webSocket.SendAsync(new ArraySegment<byte>(buffer, , received.Count),
received.MessageType, received.EndOfMessage, CancellationToken.None); received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),
CancellationToken.None);
} await webSocket.CloseAsync(webSocket.CloseStatus.Value,
webSocket.CloseStatusDescription, CancellationToken.None);
}
}
}
------------------------------------------------------------------------------------------------
OWIN keys
Request Data (OWIN v1.0.0) Key Value (type) Description
owin.RequestScheme String
owin.RequestMethod String
owin.RequestPathBase String
owin.RequestPath String
owin.RequestQueryString String
owin.RequestProtocol String
owin.RequestHeaders IDictionary<string,string[]>
owin.RequestBody Stream Request Data (OWIN v1.1.0) Key Value (type) Description
owin.RequestId String Optional Response Data (OWIN v1.0.0) Key Value (type) Description
owin.ResponseStatusCode int Optional
owin.ResponseReasonPhrase String Optional
owin.ResponseHeaders IDictionary<string,string[]>
owin.ResponseBody Stream Other Data (OWIN v1.0.0) Key Value (type) Description
owin.CallCancelled CancellationToken
owin.Version String Common Keys Key Value (type) Description
ssl.ClientCertificate X509Certificate
ssl.LoadClientCertAsync Func<Task>
server.RemoteIpAddress String
server.RemotePort String
server.LocalIpAddress String
server.LocalPort String
server.IsLocal bool
server.OnSendingHeaders Action<Action<object>,object> SendFiles v0.3.0 Key Value (type) Description
sendfile.SendAsync See delegate signature Per Request Opaque v0.3.0 Key Value (type) Description
opaque.Version String
opaque.Upgrade OpaqueUpgrade See delegate signature
opaque.Stream Stream
opaque.CallCancelled CancellationToken WebSocket v0.3.0 Key Value (type) Description
websocket.Version String
websocket.Accept WebSocketAccept See delegate signature.
websocket.AcceptAlt Non-spec
websocket.SubProtocol String See RFC6455 Section 4.2. Step 5.5
websocket.SendAsync WebSocketSendAsync See delegate signature.
websocket.ReceiveAsync WebSocketReceiveAsync See delegate signature.
websocket.CloseAsync WebSocketCloseAsync See delegate signature.
websocket.CallCancelled CancellationToken
websocket.ClientCloseStatus int Optional
websocket.ClientCloseDescription String Optional
DotNet 学习笔记 OWIN的更多相关文章
- DotNet 学习笔记 Servers
Servers ASP.NET Core ships with two different HTTP servers: •Microsoft.AspNetCore.Server.Kestrel (AK ...
- DotNet 学习笔记 应用状态管理
Application State Options --------------------------------------------------------------------- *Htt ...
- DotNet 学习笔记 MVC模型
Model Binding Below is a list of model binding attributes: •[BindRequired]: This attribute adds a mo ...
- Visual Studio 2015 Owin+MVC+WebAPI+ODataV4+EntityFrawork+Identity+Oauth2.0+AngularJS 1.x 学习笔记
2016年,.net 会有很多大更新 ASP.NET 5 在此之前我都是用着古老的.net做开发的 (WebForm + IIS) 为了接下来应对 .net 的新功能,我特地去学习了一下基本的 MVC ...
- 【工作笔记】BAT批处理学习笔记与示例
BAT批处理学习笔记 一.批注里定义:批处理文件是将一系列命令按一定的顺序集合为一个可执行的文本文件,其扩展名为BAT或者CMD,这些命令统称批处理命令. 二.常见的批处理指令: 命令清单: 1.RE ...
- Extjs 学习笔记1
学习笔记 目 录 1 ExtJs 4 1.1 常见错误处理 4 1.1.1 多个js文件中有相同的控件,切换时无法正常显示 4 1.1.2 Store的使用方法 4 1.1.3 gridPanel ...
- 黑马程序员-C#学习笔记
---------------------- ASP.Net+Android+IOS开发..Net培训.期待与您交流! ---------------------- C#学习笔记 1..NET/.do ...
- 【C#编程基础学习笔记】6---变量的命名
2013/7/24 技术qq交流群:JavaDream:251572072 教程下载,在线交流:创梦IT社区:www.credream.com [C#编程基础学习笔记]6---变量的命名 ----- ...
- ASP.NET Core Web开发学习笔记-1介绍篇
ASP.NET Core Web开发学习笔记-1介绍篇 给大家说声报歉,从2012年个人情感破裂的那一天,本人的51CTO,CnBlogs,Csdn,QQ,Weboo就再也没有更新过.踏实的生活(曾辞 ...
随机推荐
- PokeCats开发者日志(十四)——终章
已经不知道离PokeCats游戏开始开发有多少个晚上了,今晚心血来潮整理随笔的时候发现这个故事还没有划上句号. 故事的结局是最终我拿到了软著权,但是没办法上架到任何一个知名的安卓app市场,连 ...
- ZOJ 2072 K-Recursive Survival
https://vjudge.net/contest/67836#problem/K n people numbered 1 to n around a circle, we eliminate ev ...
- netbeans调试配置
apache端口8050,xdebug端口9000 1.把项目放到apache的htdocs下(一定要放在htdocs上,要么调试的时候xdebug会一直卡在“等待连接中”) 2.把php_xdebu ...
- ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction 表被锁的解决办法
转自:https://blog.csdn.net/mchdba/article/details/38313881 前言:朋友咨询我说执行简单的update语句失效,症状如下:mysql> upd ...
- SPD各模块总结
一.用户角色绑定节点 1.库存操作员.库存主管.验货操作员:绑定任一节点 2.采购操作员.公药操作员:只能绑定药库节点 3.退库操作员.药品申领员:绑定药库以外的节点 二.采购计划模块 1.采购计划的 ...
- BZOJ 2326 数学作业(分段矩阵快速幂)
实际上,对于位数相同的连续段,可以用矩阵快速幂求出最后的ans,那么题目中一共只有18个连续段. 分段矩阵快速幂即可. #include<cstdio> #include<iostr ...
- [洛谷P5166]xtq的口令
题目大意:给出一张有向图,保证任何时候边都是从编号大的向编号小连.两个操作: $1\;l\;r:$表示若编号在区间$[l,r]$内的点被染色了,问至少还需要染多少个点才可以使得整张图被染色.一个点会被 ...
- bzoj 1207: [HNOI2004]打鼹鼠 (dp)
var n,m,i,j,ans:longint; x,y,time,f:..]of longint; begin readln(n,m); to m do readln(time[i],x[i],y[ ...
- Spring-Boot基于配置按条件装Bean
背景 同一个接口有多种实现,项目启动时按某种规则来选择性的启用其中一种实现,再具体一点,比如Controller初始化的时候,根据配置文件的指定的实现类前缀,来记载具体Service,不同Servic ...
- bzoj4518: [Sdoi2016]征途(DP+决策单调性分治优化)
题目要求... 化简得... 显然m和sum^2是已知的,那么只要让sigma(si^2)最小,那就变成了求最小平方和的最小值,经典的决策单调性,用分治优化即可. 斜率优化忘得差不多就不写了 #inc ...