- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我目前看到的所有通过 web-api 使用 Microsoft WebSockets 的示例都使用 IIS,实现是在 get 方法上,HTTP 连接升级为 websocket,并且 websocket 处理程序的实例被传递到 HTTPContext
public HttpResponseMessage Get() {
if (HttpContext.Current.IsWebSocketRequest) {
var noteHandler = new NoteSocketHandler();
HttpContext.Current.AcceptWebSocketRequest(noteHandler);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
我试图实现的是在 OWIN 管道上执行相同的操作。我面临的问题是正在升级连接以使用 Websockets,但它没有使用我的 websocket 处理程序。我哪里错了?请提出建议。
Controller utilizing OwinContext (Followed the example WebSockets in Nancy using OWIN),
public HttpResponseMessage Get() {
IOwinContext owinContext = Request.GetOwinContext();
WebSocketAccept acceptToken = owinContext.Get<WebSocketAccept>("websocket.Accept");
if (acceptToken != null) {
var requestHeaders = GetValue<IDictionary<string, string[]>>(owinContext.Environment, "owin.RequestHeaders");
Dictionary<string, object> acceptOptions = null;
string[] subProtocols;
if (requestHeaders.TryGetValue("Sec-WebSocket-Protocol", out subProtocols) && subProtocols.Length > 0) {
acceptOptions = new Dictionary<string, object>();
// Select the first one from the client
acceptOptions.Add("websocket.SubProtocol", subProtocols[0].Split(',').First().Trim());
}
acceptToken(acceptOptions, async wsEnv => {
var wsSendAsync = (WebSocketSendAsync)wsEnv["websocket.SendAsync"];
var wsRecieveAsync = (WebSocketReceiveAsync)wsEnv["websocket.ReceiveAsync"];
var wsCloseAsync = (WebSocketCloseAsync)wsEnv["websocket.CloseAsync"];
var wsCallCancelled = (CancellationToken)wsEnv["websocket.CallCancelled"];
//should I pass the handler to an event?
var handler = new NoteSocketHAndler();
});
} else {
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
处理程序代码:
using System;
using Socket = Microsoft.Web.WebSockets;
using Newtonsoft.Json;
public class NoteSocketHandler : Socket.WebSocketHandler {
private static Socket.WebSocketCollection connections = new Socket.WebSocketCollection();
public NoteSocketHandler() {
}
public override void OnOpen() {
connections.Add(this);
}
public override void OnClose() {
connections.Remove(this);
}
public override void OnMessage(string message) {
ChatMessage chatMessage = JsonConvert.DeserializeObject<ChatMessage>(message);
foreach (var connection in connections) {
connection.Send(message);
}
}
}
最佳答案
我终于想出了解决问题的方法。您可以在下面找到代码,我还编写了一个使用 websockets on OWIN 的基本应用程序.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin;
namespace NoteApp.WebService.Controller {
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NoteApp.WebService.Handler;
using WebSocketAccept = System.Action<
System.Collections.Generic.IDictionary<string, object>, // WebSocket Accept parameters
System.Func< // WebSocketFunc callback
System.Collections.Generic.IDictionary<string, object>, // WebSocket environment
System.Threading.Tasks.Task>>;
using WebSocketCloseAsync = System.Func<
int, // closeStatus
string, // closeDescription
System.Threading.CancellationToken, // cancel
System.Threading.Tasks.Task>;
using WebSocketReceiveAsync = System.Func<
System.ArraySegment<byte>, // data
System.Threading.CancellationToken, // cancel
System.Threading.Tasks.Task<
System.Tuple< // WebSocketReceiveTuple
int, // messageType
bool, // endOfMessage
int>>>; // count
// closeStatusDescription
using WebSocketReceiveResult = System.Tuple<int, bool, int>;
using WebSocketSendAsync = System.Func<
System.ArraySegment<byte>, // data
int, // message type
bool, // end of message
System.Threading.CancellationToken, // cancel
System.Threading.Tasks.Task>;
public class NoteController : ApiController {
public HttpResponseMessage Get() {
IOwinContext owinContext = Request.GetOwinContext();
WebSocketAccept acceptToken = owinContext.Get<WebSocketAccept>("websocket.Accept");
if (acceptToken != null) {
var requestHeaders = GetValue<IDictionary<string, string[]>>(owinContext.Environment, "owin.RequestHeaders");
Dictionary<string, object> acceptOptions = null;
string[] subProtocols;
if (requestHeaders.TryGetValue("Sec-WebSocket-Protocol", out subProtocols) && subProtocols.Length > 0) {
acceptOptions = new Dictionary<string, object>();
// Select the first one from the client
acceptOptions.Add("websocket.SubProtocol", subProtocols[0].Split(',').First().Trim());
}
acceptToken(acceptOptions, ProcessSocketConnection);
} else {
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
private async Task ProcessSocketConnection(IDictionary<string, object> wsEnv) {
var wsSendAsync = (WebSocketSendAsync)wsEnv["websocket.SendAsync"];
var wsCloseAsync = (WebSocketCloseAsync)wsEnv["websocket.CloseAsync"];
var wsCallCancelled = (CancellationToken)wsEnv["websocket.CallCancelled"];
var wsRecieveAsync = (WebSocketReceiveAsync)wsEnv["websocket.ReceiveAsync"];
//pass the sendasync tuple and the cancellation token to the handler. The handler uses the sendasync method to send message. Each connected client has access to this
var handler = new NoteSocketHandler(wsSendAsync, CancellationToken.None);
handler.OnOpen();
var buffer = new ArraySegment<byte>(new byte[100]);
try {
object status;
while (!wsEnv.TryGetValue("websocket.ClientCloseStatus", out status) || (int)status == 0) {
WebSocketReceiveResult webSocketResultTuple = await wsRecieveAsync(buffer, CancellationToken.None);
int count = webSocketResultTuple.Item3;
handler.OnMessage(Encoding.UTF8.GetString(buffer.Array, 0, count));
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
throw ex;
}
handler.OnClose();
await wsCloseAsync((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
}
T GetValue<T>(IDictionary<string, object> env, string key) {
object value;
return env.TryGetValue(key, out value) && value is T ? (T)value : default(T);
}
}
}
关于c# - 使用 OWIN 的网络套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41848095/
我正在构建一个 MVC 5 应用程序。我需要根据 AD 和 sql 数据库或 Web 服务对人员进行身份验证。 要求是如果一个人登录到公司网络或通过 VPN 连接,我必须在不要求凭据的情况下登录它们。
有没有办法从 WindowsAzureActiveDirectoryBearerAuthenticationOptions 等扩展中调试 OWIN 中间件,并确切了解请求被拒绝的原因(例如,没有 to
我们对 Nancy/Owin 托管的 api 有一种奇怪的体验 - 当 URL 查询字符串超过 255 个字符时,Nancy 返回 400 Bad Request。 知道如何解决这个问题吗? 最佳答案
正确的处理方式是什么Content-Length在 Owin 中间件中编写正文内容时? 目前我们正在使用 context.Response.Write(data); // data is a stri
我目前正在构建一个包含多个 OWIN 中间件的库。这些中间件应该按照一定的顺序执行。在 OWIN 的第一个版本中,有 IAppBuilder界面。然而IAppBuilder不再是 OWIN 的一部分,
我们的 Mvc/WebAPI 解决方案目前有四个我们已在 ADFS3 中注册的可信身份提供者。我们的用户可以通过直接链接使用这些身份提供者中的每一个,有效地解决 ADFS 可能创建的任何家庭领域 co
实际上我知道有关于 KATANA 好处的主题和问题,我知道它们,但我的问题是 Katana 在业务方面可以为我做什么?比如为什么我应该使用 WEB API 作为一个单独的模块(中间件)?它可以与哪个中
IOwinContext 中似乎没有 HTTP Referrer,我需要捕获它。获取该特定变量的正确方法是什么? IOwinContext 有几个 Typed PEM,但我没有特别看到 referer
我正在开发一个使用 Katana 公开自托管 WebAPI 服务的应用程序。我想以类似于 IIS 允许单个网站下的多个应用程序的方式来管理内容。 例如,我可能有三个包含 web api 内容的文件夹:
从 asp.net 6 开始,将没有名为 global.asax 的文件,但 global.asax 有许多事件,例如 · Application_Init · 申请_开始 · Session_Sta
我从 http://blogs.msdn.com/b/webdev/archive/2013/11/22/debugging-owin-app-or-framework.aspx 得到了演示代码,它显
我正在使用 Facebook Owin 身份验证并或多或少地遵循 Microsoft 示例。我或多或少地关注第一次用户登录,一切正常。但如果他们退出并重试,似乎之前的 .AspNet.Correlat
我已经阅读了很多关于此的帖子,但仍然无法使其正常工作。我正在使用 Visual Studio 2013。我创建了一个新的 MVC 5 项目,并认为使用新的 facebook 登录集成会很酷。它在我的
在使用 OWIN 请求管道创建 ApplicationUserManager 时,我在使用依赖注入(inject)创建自定义 UserStore 时遇到问题。 背景 我正在尝试将 Web 应用程序中的
我试图了解 Microsoft.Owin.Security.ActiveDirectory 的用途,但似乎找不到任何文档、测试,甚至 much以文章的方式。 这个包的实际用途是什么?我试图使用它来创建
如果我使用 OwinMiddleware 和 IOwinContext 等 Microsoft.Owin 类型构建 OWIN 中间件,我的中间件是否可以与非 Microsoft Owin 主机/服务器
我在 IIS 7.5 中部署了一个 Owin 中间件身份验证项目作为 Web 应用程序但问题是 Startup.cs 没有被调用。 [assembly: OwinStartup(typeof(Auth
据我所知Microsoft.Owin.Host.SystemWeb允许我在 IIS 上运行 OWIN 应用程序,但今天我发现了另一个名为 Microsoft.Owin.Host.IIS 的包(据我从其
有谁知道将 Owin Asp.Net Identity Cookie 身份验证(本地数据库)与 Owin OpenId 身份验证(云)混合的一个很好的例子?然后用户可以选择通过创建新用户和密码(存
我将 MVC 5 与 OWIN 身份验证一起使用。 这是我的 StartUp.cs 的代码。 public void ConfigureAuth(IAppBuilder app) {
我是一名优秀的程序员,十分优秀!