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. C# HttpWebRequest post提交数据,提交对象

    1.客户端方法 //属于客户端 //要向URL Post的方法 public void PostResponse() { HttpWebRequest req = (HttpWebRequest)Ht ...

  2. #Leetcode# 700. Search in a Binary Search Tree

    https://leetcode.com/problems/search-in-a-binary-search-tree/ Given the root node of a binary search ...

  3. MapperScannerConfigurer的原理

    原文地址:http://www.mybatis.org/spring/zh/mappers.html#MapperScannerConfigurer 为了代替手工使用 SqlSessionDaoSup ...

  4. Android基础------高级ul:消息对话框

    前言:Android消息对话框提示笔记,刚刚接触Android 1.经典模式 //列表对话框 //经典模式 public void listdialog_01(View view){ final St ...

  5. SpringBoot Web(SpringMVC)

    入门工程: package com.example.demo.controller; import com.example.demo.entity.User; import org.springfra ...

  6. 【bzoj5089】最大连续子段和 分块+单调栈维护凸包

    题目描述 给出一个长度为 n 的序列,要求支持如下两种操作: A  l  r  x :将 [l,r] 区间内的所有数加上 x : Q  l  r : 询问 [l,r] 区间的最大连续子段和. 其中,一 ...

  7. BZOJ4773 负环(floyd+倍增)

    倍增floyd求出经过<=2k条边时两点间最短路,一个点到自身的最短路就是包含该点的最小环.然后倍增找答案即可.注意初始时到自身的最短路设为0,这样求出的最短路就是经过<=2k条边的而不是 ...

  8. CSS3 transform rotate(旋转)锯齿/元素抖动模糊的解决办法

    使用CSS3 3D transforms,通过GPU来渲染,能有效的起到抗锯齿效果.只要在CSS3 transform属性中加入translateZ(0).例:-webkit-transform: r ...

  9. 【以前的空间】Poj 3071 Cut the Sequence

    dp+单调性+平衡树 在看某篇论文中看到这道题,但是那篇论文不如这个http://www.cnblogs.com/staginner/archive/2012/04/02/2429850.html 大 ...

  10. 我的ACM参赛故事

    从我接触程序竞赛到现在应该有十多年了,单说ACM竞赛,从第一次非正式参赛到现在也差不多有7年多的样子.有太多的故事,想说的话,却一直没能有机会写下来.一方面是自己忙,一方面也是自己懒.所以很感谢能有人 ...