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的更多相关文章

  1. DotNet 学习笔记 Servers

    Servers ASP.NET Core ships with two different HTTP servers: •Microsoft.AspNetCore.Server.Kestrel (AK ...

  2. DotNet 学习笔记 应用状态管理

    Application State Options --------------------------------------------------------------------- *Htt ...

  3. DotNet 学习笔记 MVC模型

    Model Binding Below is a list of model binding attributes: •[BindRequired]: This attribute adds a mo ...

  4. Visual Studio 2015 Owin+MVC+WebAPI+ODataV4+EntityFrawork+Identity+Oauth2.0+AngularJS 1.x 学习笔记

    2016年,.net 会有很多大更新 ASP.NET 5 在此之前我都是用着古老的.net做开发的 (WebForm + IIS) 为了接下来应对 .net 的新功能,我特地去学习了一下基本的 MVC ...

  5. 【工作笔记】BAT批处理学习笔记与示例

    BAT批处理学习笔记 一.批注里定义:批处理文件是将一系列命令按一定的顺序集合为一个可执行的文本文件,其扩展名为BAT或者CMD,这些命令统称批处理命令. 二.常见的批处理指令: 命令清单: 1.RE ...

  6. Extjs 学习笔记1

    学习笔记 目   录 1 ExtJs 4 1.1 常见错误处理 4 1.1.1 多个js文件中有相同的控件,切换时无法正常显示 4 1.1.2 Store的使用方法 4 1.1.3 gridPanel ...

  7. 黑马程序员-C#学习笔记

    ---------------------- ASP.Net+Android+IOS开发..Net培训.期待与您交流! ---------------------- C#学习笔记 1..NET/.do ...

  8. 【C#编程基础学习笔记】6---变量的命名

    2013/7/24 技术qq交流群:JavaDream:251572072  教程下载,在线交流:创梦IT社区:www.credream.com [C#编程基础学习笔记]6---变量的命名 ----- ...

  9. ASP.NET Core Web开发学习笔记-1介绍篇

    ASP.NET Core Web开发学习笔记-1介绍篇 给大家说声报歉,从2012年个人情感破裂的那一天,本人的51CTO,CnBlogs,Csdn,QQ,Weboo就再也没有更新过.踏实的生活(曾辞 ...

随机推荐

  1. GPS定位,经纬度附近地点查询–C#实现方法

              摘要:目前的工作是需要手机查找附近N米以内的商户,功能如下图数据库中记录了商家在百度标注的经纬度(如:116.412007,39.947545),最初想法以圆心点为中心点,对半径做 ...

  2. .net 内置对象之Session对象和Session的过期时间

    QQ:827969653 有需要的朋友可以下载Session类:SessionHelper类 http://technet.microsoft.com/zh-cn/library/system.web ...

  3. 软工实践原型设计——PaperRepositories

    软工实践原型设计--PaperRepositories 写在前面 本次作业链接 队友(031602237吴杰婷)博客链接 pdf文件地址 原型设计地址(加载有点慢...) 结对成员:031602237 ...

  4. Print之modile, level

    一般print打印的design都会引入module, level. xxxprint(module, level, arg,...)... 每个Module都可以有各自的bitmap,代表这个mod ...

  5. Oracle查询字段中有空格的数据

    一.问题说明 最近在给某个用户下的表批量添加注释时,在程序中将注释名用trim()过滤一遍就可以了,但是在程序执行成功后怎么检测添加的注释名是否有空格存在呢? 二.解决方法 1.SELECT * FR ...

  6. sql 插入列放第一列

    如果是SQLSERVER 的话就这样:select * from dbo.syscolumns where id=OBJECT_ID(N'你的表名') 然后COLID这列就是列的顺序 修改这个字段就行 ...

  7. springBoot配置分析(属性和结构化)

    使用idea自带插件创建项目 一直下一步到完成 application.properties local.ip.addr = 192.168.2.110 redis.host = 192.168.3. ...

  8. byte字节的输入流 建议使用字节数组形式接受内容 因为当输入流是汉字时候 会超出字节的范围 出现无法读取的现象

    byte字节的输入流 建议使用字节数组形式接受内容 因为当输入流是汉字时候 会超出字节的范围 出现无法读取的现象

  9. CF995A Tesla

    题目描述 Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He kno ...

  10. Django Models相关

    Models的相关知识 1. AutoField:自增整数类型.根据 ID 自增长的 Int字段 2. IntegerField:整数类型 3. BigIntegerField:大整数类型.用于数值较 ...