// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            /* NLog */
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//这是为了防止中文乱码
            //loggerFactory.AddNLog();//添加NLog
            //this._env.ConfigureNLog(Path.Combine("Config", "nlog.config"));//读取Nlog配置文件
            #region NLog配置
            loggerFactory.AddNLog();                                              // 添加NLog
            //loggerFactory.ConfigureNLog(Path.Combine("Config", "nlog.config")); // 添加Nlog.config配置文件
            loggerFactory.ConfigureNLog(Path.Combine("Config", "nlogDB.config")); //把日志文件保存到数据库配置文件
            loggerFactory.AddDebug();
            #endregion
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1zzzz");
            });
            #endregion
            app.UseErrorHandling();
            #region TokenAuth
            app.UseMiddleware <JwtAuthorizationFilter>();
            #endregion
            #region 跨域
            app.UseCors("AllowAnyOrigin");      //必须位于UserMvc之前
            app.UseCors("AllowSpecificOrigin"); //必须位于UserMvc之前
            #endregion
            #region WebSockets
            var webSocketOptions = new Microsoft.AspNetCore.Builder.WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024
            };
            //webSocketOptions.AllowedOrigins.Add("https://client.com");
            //webSocketOptions.AllowedOrigins.Add("https://www.client.com");
            app.UseWebSockets(webSocketOptions);
            app.UseCustomWebSocketManager();
            #endregion

            app.UseMvc();
        }
        public static void UseGoui(this IApplicationBuilder app, string jsPath = "/Goui.js", string webSocketPath = "/Goui.ws", TimeSpan?sessionTimeout = null)
        {
            if (string.IsNullOrWhiteSpace(webSocketPath))
            {
                throw new ArgumentException("A path to be used for Goui web sockets must be specified", nameof(webSocketPath));
            }

            if (string.IsNullOrWhiteSpace(jsPath))
            {
                throw new ArgumentException("A path to be used for Goui JavaScript must be specified", nameof(jsPath));
            }

            WebSocketHandler.WebSocketPath = webSocketPath;

            if (sessionTimeout.HasValue)
            {
                WebSocketHandler.SessionTimeout = sessionTimeout.Value;
            }

            var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = WebSocketHandler.SessionTimeout,
                ReceiveBufferSize = 4 * 1024
            };

            app.UseWebSockets(webSocketOptions);

            Goui.UI.ServerEnabled = false;

            app.Use(async(context, next) =>
            {
                var response = context.Response;

                if (context.Request.Path == jsPath)
                {
                    var clientJsBytes = Goui.UI.ClientJsBytes;
                    var clientJsEtag  = Goui.UI.ClientJsEtag;
                    if (context.Request.Headers.TryGetValue("If-None-Match", out var inms) && inms.Count > 0 && inms[0] == clientJsEtag)
                    {
                        response.StatusCode = 304;
                    }
                    else
                    {
                        response.StatusCode    = 200;
                        response.ContentLength = clientJsBytes.Length;
                        response.ContentType   = "application/javascript; charset=utf-8";
                        response.Headers.Add("Cache-Control", "public, max-age=60");
                        response.Headers.Add("Etag", clientJsEtag);
                        using (var s = response.Body) {
                            await s.WriteAsync(clientJsBytes, 0, clientJsBytes.Length).ConfigureAwait(false);
                        }
                    }
                }
                else if (context.Request.Path == WebSocketHandler.WebSocketPath)
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        await WebSocketHandler.HandleWebSocketRequestAsync(context).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                    }
                }
                else if (Goui.UI.TryGetFileContentAtPath(context.Request.Path, out var file))
                {
                    if (context.Request.Headers.TryGetValue("If-None-Match", out var inms) && inms.Count > 0 && inms[0] == file.Etag)
                    {
                        response.StatusCode = 304;
                    }
                    else
                    {
                        response.StatusCode    = 200;
                        response.ContentLength = file.Content.Length;
                        response.ContentType   = file.ContentType;
                        response.Headers.Add("Cache-Control", "public, max-age=60");
                        response.Headers.Add("Etag", file.Etag);
                        using (var s = response.Body) {
                            await s.WriteAsync(file.Content, 0, file.Content.Length).ConfigureAwait(false);
                        }
                    }
                }
                else
                {
                    await next().ConfigureAwait(false);
                }
            });
        }
        /// <summary>
        /// Adds the <see cref="WebSocketMiddleware" /> to the request pipeline.
        /// </summary>
        /// <param name="app">
        /// The <see cref="IApplicationBuilder" /> to configure.
        /// </param>
        /// <param name="options">
        /// The <see cref="WebSocketOptions" /> to be used for the <see cref="WebSocketMiddleware" />.
        /// </param>
        /// <returns>
        /// The <see cref="IApplicationBuilder" />.
        /// </returns>
        public static IApplicationBuilder UseWebSockets(this IApplicationBuilder app, WebSocketOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(app.UseMiddleware <WebSocketMiddleware>(Options.Create(options)));
        }
Exemple #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4096
            };

            app.UseWebSockets();

            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/ws")
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                        while (webSocket.State == WebSocketState.Open)
                        {
                            bool recievedMessage = false;
                            MType mType          = new MType();
                            dynamic content      = null;

                            PID client_pid = new PID();

                            while (!recievedMessage)
                            {
                                byte[] buffer = new byte[4096];
                                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
                                if (!result.CloseStatus.HasValue)
                                {
                                    if (result.MessageType.HasFlag(WebSocketMessageType.Text))
                                    {
                                        string converted = Encoding.UTF8.GetString(buffer, 0, buffer.Length).Replace("\0", string.Empty);
                                        var messages     = converted.Split('}', 2, StringSplitOptions.RemoveEmptyEntries);
                                        messages[0]     += "}";

                                        try
                                        {
                                            mType = JsonSerializer.Deserialize <MType>(messages[0]);
                                        }
                                        catch (JsonException ex)
                                        {
                                            Console.WriteLine(ex.Message);
                                            mType = new MType("error");
                                            //await webSocket.SendAsync();
                                        }
                                        WebSocketMailService webSocketMailService = new WebSocketMailService(mType.MailType, messages[1]);
                                        content = webSocketMailService.HandleMessage();

                                        recievedMessage = true;
                                    }
                                }
                            }
                            switch (mType.MailType)
                            {
                            case "clientregister":
                                if (content.Username != null && content.Password != null && content.Email != null)
                                {
                                    var userDb = new Usermanager(new EditorContext());
                                    var users  = userDb.ReadAllUser();


                                    if (users.Contains(users.Find(x => x.UserName == content.Username)))
                                    {
                                        string json____ = JsonSerializer.Serialize <JsonPID>(new JsonPID(new PID(), "rejected"));
                                        byte[] buffer   = Encoding.UTF8.GetBytes(json____);
                                        await webSocket.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                                    }
                                    else
                                    {
                                        userDb.Create(content.Username, content.Password, content.Email);
                                        client_pid = _kernel.Spawn(null, Actors.ClientProxy());

                                        _kernel.Send(_sessionManager_pid, new Mail(Symbol.AddChild, client_pid));

                                        _kernel.AddWebSocketConnection(client_pid, webSocket);
                                        _websockets.Add(webSocket);
                                        string json___ = JsonSerializer.Serialize <JsonPID>(new JsonPID(client_pid, "clientlogin"));
                                        byte[] buffer  = Encoding.UTF8.GetBytes(json___);
                                        await webSocket.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                                    }

                                    var userManager = new Usermanager(new EditorContext());
                                    userManager.Create(content.Username, content.Password, content.Email);
                                    //WebSocketClient.SendMessage(webSocket, );
                                }
                                else
                                {
                                }
                                break;

                            case "clientlogin":
                                if (content.Username == "user" && content.Password == "pass")
                                {
                                    client_pid = _kernel.Spawn(null, Actors.ClientProxy());

                                    _kernel.Send(_sessionManager_pid, new Mail(Symbol.AddChild, client_pid));

                                    _kernel.AddWebSocketConnection(client_pid, webSocket);
                                    _websockets.Add(webSocket);
                                    string _json  = JsonSerializer.Serialize <JsonPID>(new JsonPID(client_pid, "clientlogin"));
                                    byte[] buffer = Encoding.UTF8.GetBytes(_json);
                                    await webSocket.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                                }
                                else
                                {
                                    string json__ = JsonSerializer.Serialize <JsonPID>(new JsonPID(client_pid, "rejected"));
                                    byte[] buffer = Encoding.UTF8.GetBytes(json__);
                                    await webSocket.SendAsync(new ArraySegment <byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                                }
                                break;

                            case "echo":
                                //should be client_pid but need to save it for each message sent!
                                _kernel.Send(_echo_pid, new Mail(Symbol.Echo, content));
                                break;

                            case "queuegame":
                                _kernel.Send(_sessionManager_pid, new Mail(Symbol.QueueGame, content));
                                break;

                            case "gameaction":
                                _kernel.Send(_sessionManager_pid, new Mail(Symbol.GameAction, content));
                                break;

                            case "items":
                                _kernel.Send(_shop_pid, new Mail(Symbol.Items, content));
                                break;

                            case "buy":
                                ///send to shop manager :)
                                _kernel.Send(_shop_pid, new Mail(Symbol.Buy, content));
                                break;

                            case "adminlist":
                                var db        = new Usermanager(new EditorContext());
                                var list      = db.ReadAllUser();
                                var listClass = new AdminList()
                                {
                                    MailType = "adminlist",
                                    Users    = new List <string>()
                                };
                                foreach (GladiatorDatabase.User s in list)
                                {
                                    listClass.Users.Add(s.UserName);
                                }
                                string json = JsonSerializer.Serialize(listClass);
                                WebSocketClient.SendMessage(webSocket, json);

                                break;

                            case "deleteuser":
                                break;

                            default:
                                break;
                            }
                            //Create client proxy
                            //await Echo(context, webSocket);
                        }
                    }
                    else
                    {
                        await next();
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemple #5
0
        // This method gets called by the runtime.
        // Use this method to configure the HTTP request pipeline.
        public void Configure(
            Microsoft.AspNetCore.Builder.IApplicationBuilder app,
            Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor
                                   | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto
            });



            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }


            app.UseDefaultFiles(
                new Microsoft.AspNetCore.Builder.DefaultFilesOptions()
            {
                DefaultFileNames = new System.Collections.Generic.List <string>()
                {
                    "index.htm", "index.html", "slick.htm"
                }
            }
                );


            app.UseStaticFiles(new StaticFileOptions()
            {
                ServeUnknownFileTypes = true,
                DefaultContentType    = "application/octet-stream",
                ContentTypeProvider   = new ExtensionContentTypeProvider(),

                OnPrepareResponse = delegate(Microsoft.AspNetCore.StaticFiles.StaticFileResponseContext context)
                {
                    // https://stackoverflow.com/questions/49547/how-do-we-control-web-page-caching-across-all-browsers

                    // The Cache-Control is per the HTTP 1.1 spec for clients and proxies
                    // If you don't care about IE6, then you could omit Cache-Control: no-cache.
                    // (some browsers observe no-store and some observe must-revalidate)
                    context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0";
                    // Other Cache-Control parameters such as max-age are irrelevant
                    // if the abovementioned Cache-Control parameters (no-cache,no-store,must-revalidate) are specified.


                    // Expires is per the HTTP 1.0 and 1.1 specs for clients and proxies.
                    // In HTTP 1.1, the Cache-Control takes precedence over Expires, so it's after all for HTTP 1.0 proxies only.
                    // If you don't care about HTTP 1.0 proxies, then you could omit Expires.
                    context.Context.Response.Headers["Expires"] = "-1, 0, Tue, 01 Jan 1980 1:00:00 GMT";

                    // The Pragma is per the HTTP 1.0 spec for prehistoric clients, such as Java WebClient
                    // If you don't care about IE6 nor HTTP 1.0 clients
                    // (HTTP 1.1 was introduced 1997), then you could omit Pragma.
                    context.Context.Response.Headers["pragma"] = "no-cache";


                    // On the other hand, if the server auto-includes a valid Date header,
                    // then you could theoretically omit Cache-Control too and rely on Expires only.

                    // Date: Wed, 24 Aug 2016 18:32:02 GMT
                    // Expires: 0

                    // But that may fail if e.g. the end-user manipulates the operating system date
                    // and the client software is relying on it.
                    // https://stackoverflow.com/questions/21120882/the-date-time-format-used-in-http-headers
                }
            });

            Microsoft.AspNetCore.Builder.WebSocketOptions webSocketOptions = new Microsoft.AspNetCore.Builder.WebSocketOptions()
            {
                KeepAliveInterval = System.TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024
            };


            app.UseWebSockets(webSocketOptions);
            app.UseOpenFolderOrFileExtensions("/OpenFolder");
            app.UseRansackSearch("/ransack");
            app.UseRansackSearchAndReplace("/sar");
            app.UseTable("/table");
            app.UseFileContents("/textfile");

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        } // End Sub Configure
Exemple #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var path = PlatformServices.Default.Application.ApplicationBasePath;

            if (!path.Contains("OData.Tests"))
            {
                //configure NLog
                loggerFactory.AddNLog(new NLogProviderOptions {
                    CaptureMessageTemplates = true, CaptureMessageProperties = true
                });
                loggerFactory.ConfigureNLog("nlog.config");
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            IEdmModel model = GetEdmModel(app.ApplicationServices);

            ODataSimplifiedOptions odata_options = new ODataSimplifiedOptions()
            {
                EnableWritingODataAnnotationWithoutPrefix = false
            };

            app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins("*"));

            app.Map("/odata/api",
                    api =>
            {
                api.UseMvc(routeBuilder =>
                {
                    routeBuilder.Select().Expand().Filter().OrderBy().MaxTop(null).Count();

                    string odata_route_name = "ODataRoute";
                    routeBuilder.MapODataServiceRoute(odata_route_name, "data", a =>
                    {
                        a.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => model);
                        a.AddService <IODataPathHandler>(Microsoft.OData.ServiceLifetime.Singleton,
                                                         sp => new DefaultODataPathHandler());
                        a.AddService <IEnumerable <IODataRoutingConvention> >(
                            Microsoft.OData.ServiceLifetime.Singleton,
                            sp => ODataRoutingConventions.CreateDefaultWithAttributeRouting(odata_route_name,
                                                                                            routeBuilder));
                        a.AddService <ODataSerializerProvider>(Microsoft.OData.ServiceLifetime.Singleton,
                                                               sp => new SampleODataSerializerProvider(sp, loggerFactory));
                        a.AddService <ODataDeserializerProvider>(Microsoft.OData.ServiceLifetime.Singleton,
                                                                 sp => new DefaultODataDeserializerProvider(sp));
                        a.AddService <ILoggerFactory>(Microsoft.OData.ServiceLifetime.Singleton,
                                                      sp => loggerFactory);
                        a.AddService <ODataSimplifiedOptions>(Microsoft.OData.ServiceLifetime.Singleton,
                                                              sp => odata_options);
                        a.AddService <ODataPayloadValueConverter, SampleODataPayloadValueConverter>(Microsoft.OData
                                                                                                    .ServiceLifetime.Singleton);
                    });
                    routeBuilder.EnableDependencyInjection();
                });
            });

            var webSocketOptions = new Microsoft.AspNetCore.Builder.WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(5),
                ReceiveBufferSize = 999999
            };
        }