webapi正常都托管在iis上,这里引入owin,将其托管在window服务上。
第一步:创建一个服务,这里就不多描述。
第二步:引入OWIN
2.1引入bll
2.2加入api路由配置
public class Startup { public void Configuration(IAppBuilder appBuilder) { HttpConfiguration config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //添加允许跨域 var CorsConfig = new EnableCorsAttribute(origins: "*", headers: "*", methods: "*") { PreflightMaxAge = 1800, SupportsCredentials = true }; config.EnableCors(CorsConfig); appBuilder.UseWebApi(config); } }
2.3监听ip和端口
protected override void OnStart(string[] args) { _server = WebApp.Start<Startup>(url: "http://192.168.200.84:2000/"); Console.WriteLine("Service start success..."); }
第三步:加入webapi接口
namespace WebSocketService.Controllers { public class HomeController : HomeControllerBase { } }
基类:
namespace GameCommon.Controllers { public class HomeControllerBase : ApiController { [HttpGet] public object Get() { return new { Age=12,Name="Holle world"}; } [HttpPost] public object Post() { return new { Age = 12, Name = "Holle world" }; } } }
我这里将接口单独提取了一个DLL文件来处理。
项目结构:
另外这里再贴上webSocket的代码:
using GameCommon.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebSocketService.Controllers { public class ConnectController:ConnectControllerBase { } }
基类:
using Microsoft.Owin; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace GameCommon.Controllers { using WebSocketAccept = System.Action<System.Collections.Generic.IDictionary<string, object>,System.Func< System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>>; public class ConnectControllerBase : ApiController { [HttpGet] public HttpResponseMessage Connect() { try { if (Request.Method != HttpMethod.Get) { return new HttpResponseMessage(HttpStatusCode.NotFound); } IOwinContext owinContext = Request.GetOwinContext(); WebSocketAccept acceptToken = owinContext.Get<WebSocketAccept>("websocket.Accept"); if (acceptToken != null) { acceptToken(null, ProcessSocketConnection); } else { return new HttpResponseMessage(HttpStatusCode.BadRequest); } return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } } public async Task ProcessSocketConnection(IDictionary<string, object> wsEnv) { WebSocket wSocket = ((HttpListenerWebSocketContext)wsEnv["System.Net.WebSockets.WebSocketContext"]).WebSocket; while (true) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[10240]); WebSocketReceiveResult receivedResult; receivedResult = await wSocket.ReceiveAsync(buffer, CancellationToken.None); if (receivedResult.MessageType == WebSocketMessageType.Close) { await wSocket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None); break; } if (wSocket.State == WebSocketState.Open) { string receivedJson = Encoding.UTF8.GetString(buffer.Array, 0, receivedResult.Count); } } } } }