我使用CefSharp在Windows窗体中托管浏览器,不再触发Owin AppBuilder.Use方法。我是自托管Web API。这段代码工作正常,但只是停止工作,没有抛出异常。 CefSharp浏览器中的错误是'websocket connection refused'。
我已尝试从Chrome浏览器调用此代码,但它可以正常运行。 websockets连接没有问题。
using WebSocketAccept = Action<IDictionary<string, object>, Func<IDictionary<string, object>, Task>>;
public static class WebApiStartup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public static void Configuration(IAppBuilder appBuilder, IUnityContainer unityContainer)
{
var config = new HttpConfiguration
{
DependencyResolver = new UnityDependencyResolver(unityContainer)
};
// JSONP formatter
var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
config.Formatters.Add(jsonpFormatter);
// JSON formatter
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
// If need to convert enum to string add StringEnumConverter to the settings
// config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter())
// CORS
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
//JSON Camel Case
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
appBuilder.Use((context, next) =>
{
var accept = context.Get<WebSocketAccept>("websocket.Accept");
if (accept == null)
{
// Not a websocket request
return next();
}
var requestHeaders = GetValue<IDictionary<string, string[]>>(context.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>
{
{"websocket.SubProtocol", subProtocols[0].Split(',').First().Trim()} // Select the first one from the client
};
}
var controllerMainScreen = new MainScreenController(unityContainer.Resolve<ILogRepository>());
accept(acceptOptions, controllerMainScreen.ProcessSocketConnection);
return Task.FromResult<object>(null);
});
appBuilder.UseWebApi(config);
}
static T GetValue<T>(IDictionary<string, object> env, string key)
{
object value;
return env.TryGetValue(key, out value) && value is T ? (T)value : default(T);
}
关于在哪里调试/修复此问题的任何建议?这一行
从Chrome浏览器调用时,accept(acceptOptions,controllerMainScreen.ProcessSocketConnection);
被调用并正确执行。这段代码突然停止工作,没有抛出异常。