Esempio n. 1
0
 public void ProcessRequest(HttpContext context)
 {
     string op = context.Request["op"];
     if (!string.IsNullOrWhiteSpace(op)) {
         switch (op.ToLower()) {
             case "list":
                 RolesListJSON(context);
                 break;
             case "right":
                 RightJSON(context);
                 break;
             case "add":
                 Add(context);
                 break;
             case "delete":
                 Delete(context);
                 break;
             case "update-n":
                 UpdateRoleName(context);
                 break;
             case "update-r":
                 UpdateRight(context);
                 break;
             case "del-employee":
                 RemoeEmployee(context);
                 break;
         }
     }
 }
		public DefaultAuthenticationEventArgs (HttpContext context)
		{
			if (context == null)
				throw new ArgumentNullException ("context");

			_context = context;
		}
Esempio n. 3
0
    public void ProcessRequest(HttpContext context)
    {
        // Example of using a passed in value in the query string to set a categoryId
        // Now you can do anything you need to witht the file.
        //int categoryId = 0;
        //if (!string.IsNullOrEmpty(context.Request.QueryString["CategoryID"]))
        //{
        //    int.TryParse(context.Request.QueryString["CategoryID"],out categoryId);
        //}
        //if (categoryId > 0)
        //{
        //}

            // get the applications path

        string uploadPath = context.Server.MapPath(context.Request.ApplicationPath + "/Upload");
        // loop through all the uploaded files
        for(int j = 0; j < context.Request.Files.Count; j++)
        {
            // get the current file
            HttpPostedFile uploadFile = context.Request.Files[j];
            // if there was a file uploded
            if (uploadFile.ContentLength > 0)
            {
                // save the file to the upload directory

                //use this if testing from a classic style upload, ie.

                // <form action="Upload.axd" method="post" enctype="multipart/form-data">
                //    <input type="file" name="fileUpload" />
                //    <input type="submit" value="Upload" />
                //</form>

                // this is because flash sends just the filename, where the above
                //will send the file path, ie. c:\My Pictures\test1.jpg
                //you can use Test.thm to test this page.
                //string filename = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf("\\"));
                //uploadFile.SaveAs(string.Format("{0}{1}{2}", tempFile, "Upload\\", filename));

                // use this if using flash to upload
                uploadFile.SaveAs(Path.Combine(uploadPath, uploadFile.FileName));

                // HttpPostedFile has an InputStream also.  You can pass this to
                // a function, or business logic. You can save it a database:

                //byte[] fileData = new byte[uploadFile.ContentLength];
                //uploadFile.InputStream.Write(fileData, 0, fileData.Length);
                // save byte array into database.

                // something I do is extract files from a zip file by passing
                // the inputStream to a function that uses SharpZipLib found here:
                // http://www.icsharpcode.net/OpenSource/SharpZipLib/
                // and then save the files to disk.
            }
        }

        // Used as a fix for a bug in mac flash player that makes the
        // onComplete event not fire
        HttpContext.Current.Response.Write(" ");
    }
Esempio n. 4
0
    void Add(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        string name = context.Request["text"];
        string msg = string.Empty;
        if (!string.IsNullOrWhiteSpace(name)) {
            try {
                Guid id= System.Guid.NewGuid() ;
                IList<Module> modules = RepositoryFactory<Modules>.Get().GetAll();
                var query = from p in modules
                            select new Right { ModuleId = p.Id , Permission = 0 , RoleId = id };

                Role obj = new Role { Id =id, Name = context.Server.UrlDecode(name),Rights=query.ToList() };
                RepositoryFactory<RolesRepository>.Get().Add(obj);
                context.Response.Write("{\"id\":\"" + obj.Id.ToString() + "\"}");

                AppLog.Write("创建角色", AppLog.LogMessageType.Info,"name="+obj.Name,this.GetType());
            } catch (Exception ex) {

                AppLog.Write("创建角色 出错" , AppLog.LogMessageType.Error , "name=" + name , ex , this.GetType());

                msg = ex.Message;
            }
        } else {
            msg = "角色名不能为空";
        }
        if (!string.IsNullOrWhiteSpace(msg)) {
            context.Response.Write("{\"msg\":\""+msg+"\"}");
        }
    }
Esempio n. 5
0
        public Task Invoke(HttpContext context)
        {
            var path = context.Request.Path.Value.TrimStart('/');

            var response = context.Response;
            if (path == "topics.js")
            {
                response.Headers["content-type"] = "text/javascript";
                return response.WriteAsync(_topicJS);
            }

            var topic = _project.FindTopicByUrl(path);
            if (topic == null)
            {
                response.StatusCode = 404;
                response.Headers["content-type"] = "text/plain";

                return response.WriteAsync("Unknown topic");
            }

            response.Headers["cache-control"] = "no-cache, no-store, must-revalidate";
            response.Headers["pragma"] = "no-cache";
            response.Headers["expires"] = "0";

            var html = GenerateHtml(topic);

            response.Headers["content-type"] = "text/html";

            return response.WriteAsync(html);
        }
            public void OnActionExecuted(HttpContext httpContext, Action baseAction)
            {
                DetermineRequestType(HttpContext.Current.Request);

                switch (_requestType)
                {
                    case CrossOriginRequestType.Cors:
                        // If the Origin header is in the request, then process this as a CORS request
                        // Let the default filter process the request
                        baseAction();

                        // Add response headers for the CORS request
                        var response = httpContext.Response;

                        // Allow all origins
                        response.AppendHeader(AccessControlAllowOriginHeader, _origin);
                        response.AppendHeader(AccessControlAllowCredentials, "true");

                        break;

                    default:
                        baseAction();

                        break;
                }
            }
Esempio n. 7
0
		override object Evaluate (HttpContext ctx, Control control)
		{
			if (control == null)
				return null;
			if (control.Page == null)
				return null;
			
			if(String.IsNullOrEmpty(ControlID))
				throw new ArgumentException ("The ControlID property is not set.");

			Control c = null, namingContainer = control.NamingContainer;
			
			while (namingContainer != null) {
				c = namingContainer.FindControl(ControlID);
				if (c != null)
					break;
				namingContainer = namingContainer.NamingContainer;
			}
			if (c == null)
				throw new InvalidOperationException ("Control '" + ControlID + "' not found.");

			string propName = PropertyName;
			if (String.IsNullOrEmpty (propName)) {
				object [] attrs = c.GetType ().GetCustomAttributes (typeof (ControlValuePropertyAttribute), true);
				if(attrs.Length==0)
					throw new ArgumentException ("The PropertyName property is not set and the Control identified by the ControlID property is not decorated with a ControlValuePropertyAttribute attribute.");
				ControlValuePropertyAttribute attr = (ControlValuePropertyAttribute) attrs [0];
				propName = attr.Name;
 			}
			
			return DataBinder.Eval (c, propName);
		}
        public async Task Invoke(HttpContext context)
        {
            string language = context.Session.GetString("Language");

            if (language == null)
            {
                language = GlobalConstants.DefaultLanguage;
            }            

            var defaultCulture = new CultureInfo(language);

            SetCurrentCulture(defaultCulture);
            app.UseRequestLocalization(new RequestLocalizationOptions()
            {
                SupportedCultures = new List<CultureInfo>()
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("en-GB"),
                    new CultureInfo("bg"),
                },
                SupportedUICultures = new List<CultureInfo>()
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("en-GB"),
                    new CultureInfo("bg"),
                },
                DefaultRequestCulture = new RequestCulture(CultureInfo.CurrentCulture)
            });

            await next(context);
        }
Esempio n. 9
0
        public async Task<CorsPolicy> GetPolicyAsync(HttpContext context, string policyName)
        {
            var path = context.Request.Path.ToString();
            var origin = context.Request.Headers["Origin"].First();
            var thisOrigin = context.Request.Scheme + "://" + context.Request.Host;

            // see if the Origin is different than this server's origin. if so
            // that indicates a proper CORS request. some browsers send Origin
            // on POST requests.
            // todo: do we still need this check?
            if (origin != null && origin != thisOrigin)
            {
                if (IsPathAllowed(path))
                {
                    _logger.LogInformation("CORS request made for path: {0} from origin: {1}", path, origin);

                    if (await _corsPolicyService.IsOriginAllowedAsync(origin))
                    {
                        _logger.LogInformation("CorsPolicyService allowed origin");
                        return Allow(origin);
                    }
                    else
                    {
                        _logger.LogInformation("CorsPolicyService did not allow origin");
                    }
                }
                else
                {
                    _logger.LogWarning("CORS request made for path: {0} from origin: {1} but rejected because invalid CORS path", path, origin);
                }
            }

            return null;
        }
Esempio n. 10
0
        private static async Task HandleWebSocketsAsync(HttpContext context, Func<Task> next)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await next();
                return;
            }

            var hub = context.RequestServices.GetRequiredService<MessageHub>();

            using (var webSocket = await context.WebSockets.AcceptWebSocketAsync())
            {
                try
                {
                    await hub.SubscribeAsync(webSocket);

                    var buffer = new ArraySegment<byte>(new byte[4096]);

                    while (webSocket?.State == WebSocketState.Open)
                    {
                        await webSocket.ReceiveAsync(buffer, CancellationToken.None);
                    }
                }
                finally
                {
                    await hub.UnsubscribeAsync(webSocket);
                }
            }
        }
Esempio n. 11
0
 private void RetrieveFileData(HttpContext context, string filePath, string container)
 {
     MediaFileModel resultModel = new MediaFileModel();
     // only send request to imageprocessor if querystring exists; can exclude other parameters if needed
     if (context.Request.RawUrl.Contains("?"))
     {
         resultModel = MediaHelper.GetMediaFile(filePath, container, context.Request.RawUrl);
     }
     else
     {
         resultModel = MediaHelper.GetMediaFile(filePath, container);
     }
     if (resultModel.RedirectToAzureStorage)
     {
         context.Response.Redirect(filePath.Replace($"/{container}", $"{ConfigurationManager.AppSettings["BlobStorage"]}/{container}"), true);
     }
     var myTimeSpan = new TimeSpan(7, 0, 0, 0);
     context.Response.Cache.SetCacheability(HttpCacheability.Public);
     context.Response.Cache.SetValidUntilExpires(true);
     context.Response.Cache.SetMaxAge(myTimeSpan);
     context.Response.Cache.SetLastModified(resultModel.LastModifiedDate);
     context.Response.Cache.SetETag(resultModel.ETag.Replace("\\\"", ""));
     context.Response.AddHeader("Content-MD5", resultModel.ContentMd5);
     context.Response.ContentType = resultModel.ContentType;
     // replicate properties returned by blob storage
     context.Response.AddHeader("Server", "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0");
     context.Response.AddHeader("x-ms-request-id", Guid.NewGuid().ToString());
     context.Response.AddHeader("x-ms-version", "2009-09-19");
     context.Response.AddHeader("x-ms-lease-status", "unlocked");
     context.Response.AddHeader("x-ms-blob-type", "BlockBlob");
     context.Response.OutputStream.Write(resultModel.ImageData, 0, resultModel.ImageData.Length);
     context.Response.AddHeader("Content-Length", resultModel.ImageData.Length.ToString());
     context.Response.Flush();
     context.Response.End();
 }
Esempio n. 12
0
    private static void Save(HttpContext context, Post post)
    {
        string name = context.Request.Form["name"];
        string email = context.Request.Form["email"];
        string website = context.Request.Form["website"];
        string content = context.Request.Form["content"];

        Validate(name, email, content);

        Comment comment = new Comment()
        {
            Author = name.Trim(),
            Email = email.Trim(),
            Website = GetUrl(website),
            Ip = context.Request.UserHostAddress,
            UserAgent = context.Request.UserAgent,
            IsAdmin = context.User.Identity.IsAuthenticated,
            Content = HttpUtility.HtmlEncode(content.Trim()).Replace("\n", "<br />"),
        };

        post.Comments.Add(comment);
        post.Save();

        string wrapper = VirtualPathUtility.ToAbsolute("~/views/commentwrapper.cshtml") + "?postid=" + post.ID + "&commentid=" + comment.ID;
        context.Response.Write(wrapper);
    }
        public Task Invoke(HttpContext httpContext)
        {
            var clientManager = httpContext.RequestServices.GetService<ClientManager>();
            clientManager.Init(httpContext);

            return _next(httpContext);
        }
        public async Task Invoke(HttpContext context)
        {
            var responseBody = context.Response.Body;
            var requestBody = context.Request.Body;

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                // TODO: Add the feature interface to disable this memory stream
                // when we add signalr
                context.Response.Body = new MemoryStream();
                context.Request.Body = new MemoryStream();

                await requestBody.CopyToAsync(context.Request.Body);

                LogRequest(context);

            }

            var stopwatch = Stopwatch.StartNew();
            await _next(context);
            stopwatch.Stop();

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                LogResponse(context);

                await context.Response.Body.CopyToAsync(responseBody);

            }
            _logger.LogInformation(context.Request.Path + ": " + context.Response.StatusCode + " " + stopwatch.ElapsedMilliseconds + "ms");
        }
        /// <summary>
        /// This examines the request to see if it matches a configured directory, and if there are any files with the
        /// configured default names in that directory.  If so this will append the corresponding file name to the request
        /// path for a later middleware to handle.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext context)
        {
            IEnumerable<IFileInfo> dirContents;
            PathString subpath;
            if (Helpers.IsGetOrHeadMethod(context.Request.Method)
                && Helpers.TryMatchPath(context, _matchUrl, forDirectory: true, subpath: out subpath)
                && _options.FileSystem.TryGetDirectoryContents(subpath.Value, out dirContents))
            {
                // Check if any of our default files exist.
                for (int matchIndex = 0; matchIndex < _options.DefaultFileNames.Count; matchIndex++)
                {
                    string defaultFile = _options.DefaultFileNames[matchIndex];
                    IFileInfo file;
                    // TryMatchPath will make sure subpath always ends with a "/" by adding it if needed.
                    if (_options.FileSystem.TryGetFileInfo(subpath + defaultFile, out file))
                    {
                        // If the path matches a directory but does not end in a slash, redirect to add the slash.
                        // This prevents relative links from breaking.
                        if (!Helpers.PathEndsInSlash(context.Request.Path))
                        {
                            context.Response.StatusCode = 301;
                            context.Response.Headers[Constants.Location] = context.Request.PathBase + context.Request.Path + "/";
                            return Constants.CompletedTask;
                        }

                        // Match found, re-write the url. A later middleware will actually serve the file.
                        context.Request.Path = new PathString(context.Request.Path.Value + defaultFile);
                        break;
                    }
                }
            }

            return _next(context);
        }
 private void UnregisterClient(HttpContext context)
 {
     var client = _clients.SingleOrDefault(hc => hc.Context == context);
     _clients.Remove(client);
     _logger.LogInformation("Client [{0}] disconnected", client.Description);
     client.CompletionSource.SetResult(null);
 }
Esempio n. 17
0
        public static bool HandleAuthentication(HttpContext context)
        {
            string authType = context.Request.QueryString["auth"];
            string user = context.Request.QueryString["user"];
            string password = context.Request.QueryString["password"];
            string domain = context.Request.QueryString["domain"];

            if (string.Equals("basic", authType, StringComparison.OrdinalIgnoreCase))
            {
                if (!HandleBasicAuthentication(context, user, password, domain))
                {
                    context.Response.End();
                    return false;
                }
            }
            else if (string.Equals("Negotiate", authType, StringComparison.OrdinalIgnoreCase) ||
                string.Equals("NTLM", authType, StringComparison.OrdinalIgnoreCase))
            {
                if (!HandleChallengeResponseAuthentication(context, authType, user, password, domain))
                {
                    context.Response.End();
                    return false;
                }
            }
            else if (authType != null)
            {
                context.Response.StatusCode = 501;
                context.Response.StatusDescription = "Unsupported auth type: " + authType;
                context.Response.End();
                return false;
            }

            return true;
        }
        public async Task Invoke(HttpContext context)
        {
            /* filter out our requests */
            if (context.Request.Method != "GET")
            {
                await _next(context);
                return;
            }

            if (context.Request.Path != "/__webpack_hmr")
            {
                await _next(context);
                return;
            }

            /* set some headers to force the response to auto-chunk and keep-alive */
            context.Response.Headers["Cache-Control"] = "no-cache, no-transform";
            context.Response.Headers["Connection"] = "keep-alive";
            context.Response.ContentType = "text/event-stream;charset=utf-8";

            /* register the client to receive events */
            var client = RegisterClient(context);

            /* 
               This only completes when the client disconnects,
               so the connection is kept open.
            */
            await client.CompletionSource.Task;
            
            /*
               This prevents HttpFrame.WriteChunkedResponseSuffix from throwing
               an EPIPE error with stacktrace due to the socket being disconnected
            */
            throw new QuietException("Redouble.AspNet.Webpack.HotReload: client disconnected");
        }
 private HmrClient RegisterClient(HttpContext context)
 {
     var client = new HmrClient(context);
     _clients.Add(client);
     _logger.LogInformation("Client [{0}] connected", client.Description);
     return client;
 }
Esempio n. 20
0
 // 1. Find tenant by hostname.
 // 2. If context not created - create it.
 public async Task Invoke(HttpContext context)
 {
     var tenant = _tenantSelector.SelectTenant(context);
     
     if (tenant != null)
     {
         _logger.LogInformation($"Found appropriate tenant: {tenant.TenantId}");
         var tenantContext = _host.LoadContext(tenant);
         var tenantServiceProvider = tenantContext.Services;
         var pipeline = tenantContext.States.Get<RequestDelegate>();
         
         if (pipeline == null)
         {
             _logger.LogInformation($"Creating pipeline for tenant: {tenant.TenantId}");
             var pipelineFactory = tenantServiceProvider.GetRequiredService<ITenantPipelineFactory>();
             pipeline = pipelineFactory.CreatePipeline();
             tenantContext.States.Set(pipeline);
             var eventBus = tenantServiceProvider.GetRequiredService<IEventBus>();
             await eventBus.NotifyAsync<ITenantEvents>(e => e.ActivatedAsync());
         }
         
         using (var scope = tenantServiceProvider.CreateScope())
         {
             context.RequestServices = scope.ServiceProvider;
             context.Features.Set(tenantContext);
             await pipeline(context);
         }
     }
     else
     {
         _logger.LogWarning("Appropriate tenant not found, continue executing pipeline.");
         await _next(context);
     }
 }
Esempio n. 21
0
        public async Task Invoke(HttpContext context)
        {
            StringValues forwarededProto;
            if (context.Request.Headers.TryGetValue("X-Forwarded-Proto", out forwarededProto))
            {
                _logger.LogDebug($"Rewriting scheme to {forwarededProto}");

                context.Request.Scheme = forwarededProto;
            }

            StringValues forwardedFor;
            if (context.Request.Headers.TryGetValue("X-Forwarded-For", out forwardedFor))
            {
                var address = forwardedFor.ToString().Split(',').First().Trim();

                _logger.LogDebug($"Rewriting remoteip to {address}");

                IPAddress addr;
                if (IPAddress.TryParse(address, out addr))
                {
                    context.Request.HttpContext.Connection.RemoteIpAddress = addr;
                }
            }

            await _next(context);
        }
        public async Task Invoke(HttpContext httpContext, RequestTelemetry telemetry)
        {
            telemetry.Timestamp = DateTimeOffset.UtcNow;

            var sw = new Stopwatch();
            sw.Start();

            bool requestFailed = false;

            try
            {
                await this.next.Invoke(httpContext);
            }
            catch (Exception)
            {
                requestFailed = true;
                throw;
            }
            finally
            {
                sw.Stop();

                telemetry.Duration = sw.Elapsed;
                telemetry.ResponseCode = httpContext.Response.StatusCode.ToString();
                telemetry.Success = (!requestFailed) && (httpContext.Response.StatusCode < 400);
                telemetry.HttpMethod = httpContext.Request.Method;
                telemetry.Url = httpContext.Request.GetUri();
                telemetry.Context.GetInternalContext().SdkVersion = this.sdkVersion;
                    
                this.telemetryClient.TrackRequest(telemetry);
            }
        }
Esempio n. 23
0
 public void ProcessRequest(HttpContext context)
 {
     System.Drawing.Image Cover;
     //判断请求的物理路径中,是否存在文件
     if (File.Exists(context.Request.PhysicalPath))
     {
         //加载文件
         Cover = Image.FromFile(context.Request.PhysicalPath);
         //加载水印图片
         Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));
         //实例化画布
         Graphics g = Graphics.FromImage(Cover);
         //在image上绘制水印
         g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
         //释放画布
         g.Dispose();
         //释放水印图片
         watermark.Dispose();
     }
     else
     {
         //加载默认图片
         Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
     }
     //设置输出格式
     context.Response.ContentType = "image/jpeg";
     //将图片存入输出流
     Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
     Cover.Dispose();
     context.Response.End();
 }
Esempio n. 24
0
 public AppendCookieContext(HttpContext context, CookieOptions options, string name, string value)
 {
     Context = context;
     CookieOptions = options;
     CookieName = name;
     CookieValue = value;
 }
 public void ProcessRequest(HttpContext context)
 {
     MoSmsResp moSmsResp = null;
     string jsonString="";
     context.Response.ContentType = "application/json";
     try
     {
         byte[] PostData = context.Request.BinaryRead(context.Request.ContentLength);
         jsonString = Encoding.UTF8.GetString(PostData);
         JavaScriptSerializer json_serializer = new JavaScriptSerializer();
         MoSmsReq moSmsReq = json_serializer.Deserialize<MoSmsReq>(jsonString);
         moSmsResp = GenerateStatus(true);
         onMessage(moSmsReq);
     }
     catch (Exception)
     {
         moSmsResp = GenerateStatus(false);
     }
     finally
     {
         if (jsonString.Equals(""))
             context.Response.Write(APPLICATION_RUNING_MESSAGE);
         else
             context.Response.Write(moSmsResp.ToString());
     }
 }
        public async Task Invoke(HttpContext httpContext)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Begin Routing Request");
            }

            var shellSettings = (ShellSettings)httpContext.Features[typeof(ShellSettings)];

            RequestDelegate pipeline;

            if (!_pipelines.TryGetValue(shellSettings.Name, out pipeline))
            {
                // Building a pipeline can't be done by two requests
                lock (_pipelines)
                {
                    if (!_pipelines.TryGetValue(shellSettings.Name, out pipeline))
                    {
                        pipeline = BuildTenantPipeline(shellSettings, httpContext.RequestServices);

                        if (shellSettings.State == Environment.Shell.Models.TenantState.Running)
                        {
                            // TODO: Invalidate the pipeline automatically when the shell context is changed
                            // such that we can reload the middlewares and the routes. Implement something similar
                            // to IRunningShellTable but for the pipelines.

                            _pipelines.Add(shellSettings.Name, pipeline);
                        }
                    }
                }
            }

            await pipeline.Invoke(httpContext);
        }
Esempio n. 27
0
 /// <summary>
 /// Main constructor to create <see cref="BasicAuthInfo"/>
 /// </summary>
 /// <param name="credential">Basic auth credential from the request</param>
 /// <param name="properties">Basic auth properties from the request</param>
 /// <param name="httpContext">Context from the request</param>
 /// <param name="authenticationScheme">Authentication scheme from the configuration</param>
 internal BasicAuthInfo(BasicAuthCredential credential, AuthenticationProperties properties, HttpContext httpContext, string authenticationScheme)
 {
     this.Credential = credential;
     this.Properties = properties;
     this.HttpContext = httpContext;
     this.AuthenticationScheme = authenticationScheme;
 }
Esempio n. 28
0
        async Task ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "application/json; charset=utf-8";
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                string code = context.Request.Query["code"];
                if (code == null)
                {
#if !DEBUG
                    context.Response.Redirect("https://silentorbit.com/lax/");
#endif
                    await context.Response.WriteAsync("{\"error\": \"no code\"}");
                    return;
                }
                var response = WebCompiler.Compile(code);
                string json = JsonConvert.SerializeObject(response, Formatting.Indented);
                await context.Response.WriteAsync(json);
            }
            catch (Exception ex)
            {
                await context.Response.WriteAsync(ex.Message);
            }
        }
Esempio n. 29
0
    public void ProcessRequest(HttpContext context)
    {
        if (!WebUser.IsAuthenticated)
        {
            throw new HttpException(401, "You must login to do this.");
        }

        if (!WebUser.HasRole(UserRoles.Admin))
        {
            throw new HttpException(401, "You do not have permission to do this.");
        }

        var mode = context.Request.Form["mode"];
        var name = context.Request.Form["roleName"];
        var id = context.Request.Form["roleId"];

        if (mode == "edit")
        {
            Edit(Convert.ToInt32(id), name);
        }
        else if (mode == "new")
        {
            Create(name);
        }
        else if (mode == "delete")
        {
            Delete(name);
        }

        context.Response.Redirect("~/admin/role/");
    }
 async Task OnLogin(HttpContext ctx)
 {
     LoginWasCalled = true;
     await ReadSignInMessage(ctx);
     await IssueLoginCookie(ctx);
     await CreateSignInResponse(ctx);
 }
Esempio n. 31
0
 private static Task HandleExceptionAsync(HttpContext context, Exception exception)
 {
     return context.Response.WriteAsync("ScMWare Errors!");
 }
Esempio n. 32
0
		public override void ToDo(HttpContext context)
		{
			WriteToResponse(new JsonObject(new Dictionary<string, object> {
				{"success", true }
			}), context);
		}
Esempio n. 33
0
 public static T Request <T>(this HttpContext context, string parameter) where T : class
 {
     return(context.RequestString(parameter)?.DeserializeObject <T>());
 }
Esempio n. 34
0
 /// <summary>
 /// 是否为ajax请求
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public static bool IsAjaxRequest(this HttpContext context)
 {
     return(context.Request("X-Requested-With") == "XMLHttpRequest" ||
            (context.Request.Headers != null &&
             context.Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
 }
Esempio n. 35
0
 public static IApplicationBuilder UserItem04(this IApplicationBuilder builder, HttpContext http)
 {
     builder.Use(next =>
     {
         return(new RequestDelegate((d) =>
         {
             Console.WriteLine("我是item04方法");
             return next(http);
         }));
     });
     return(builder);
 }
Esempio n. 36
0
        public void ProcessRequest(HttpContext context)
        {
            var file      = context.Request.FilePath.Replace(".ashx", String.Empty);
            var fileName  = file.Substring(file.LastIndexOf('/') + 1);
            var extension = file.Substring(file.LastIndexOf('.'));

            int width;
            int height;

            int.TryParse(context.Request["w"], out width);
            int.TryParse(context.Request["h"], out height);

            var path = context.Server.MapPath(file);

            if (!File.Exists(path))
            {
                context.Response.StatusCode = 404;
                context.Response.End();
                return;
            }
            context.Response.Clear();
            context.Response.Cache.SetExpires(DateTime.Now.AddDays(10));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetValidUntilExpires(false);
            context.Response.AddHeader("content-disposition", "inline;filename=" + fileName);

            using (var fs = new FileStream(path,
                                           FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var img = new Bitmap(fs))
                {
                    using (var ms = new MemoryStream())
                    {
                        Bitmap bmpOut = null;

                        if (width > 0 && height == 0)
                        {
                            double tmp = img.Height / (double)img.Width;
                            bmpOut = GenerateThumb(img, width, (int)(width * tmp));
                        }
                        if (height > 0 && width == 0)
                        {
                            double tmp = img.Width / (double)img.Height;
                            bmpOut = GenerateThumb(img, (int)(height * tmp), height);
                        }
                        if (height > 0 && width > 0)
                        {
                            bmpOut = GenerateThumb(img, width, height);
                        }
                        if (height == 0 && width == 0)
                        {
                            bmpOut = GenerateThumb(img, img.Width, img.Height);
                        }
                        if (GetContentType(extension) == "image/jpeg")
                        {
                            var info = ImageCodecInfo.GetImageEncoders();
                            var encoderParameters = new EncoderParameters(1);
                            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                            if (bmpOut != null)
                            {
                                bmpOut.Save(ms, info[1], encoderParameters);
                            }
                        }
                        else if (bmpOut != null)
                        {
                            bmpOut.Save(ms, GetImageFormat(extension));
                        }
                        var arrImg = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(arrImg, 0, (int)ms.Length);
                        img.Dispose();
                        context.Response.ContentType = GetContentType(extension);

                        context.Response.BinaryWrite(arrImg);
                        context.Response.End();
                    }
                }
            }
        }
 public static bool ValidarClaimsUsuario(HttpContext context, string claimName, string claimValue)
 {
     return context.User.Identity.IsAuthenticated &&
            context.User.Claims.Any(c => c.Type == claimName && c.Value.Contains(claimValue));
 }
Esempio n. 38
0
        /// <summary>
        /// Set the UI language
        /// </summary>
        public void ChangeUiLanguage(HttpContext context, string language)
        {
            string culture = SetCulture(language);

            UpdateCultureCookie(context, culture);
        }
Esempio n. 39
0
        private void editContact()
        {
            try
            {
                ContactsService      contactsService = new ContactsService(SessionManager.sessionMemberInfo);
                Contact              editedContact   = new Contact();
                TransactionResultDTO result;

                // Variables to manage the contact pic file
                string fileExtension   = "";
                int    fileSizeInBytes = 0;

                if (uplContactPic.HasFile)
                {
                    fileExtension   = System.IO.Path.GetExtension(uplContactPic.FileName);
                    fileSizeInBytes = uplContactPic.PostedFile.ContentLength;

                    if (!Validations.isValidContactPic(fileExtension, fileSizeInBytes))
                    {
                        showError(HttpContext.GetGlobalResourceObject("Resource", "ErrorFotoContactoInvalida").ToString());
                        return;
                    }
                }

                editedContact.id             = Convert.ToInt32(Request.QueryString[Parameters.id]);
                editedContact.firstName      = txtFirstName.Text;
                editedContact.lastName       = txtLastName.Text;
                editedContact.genre          = ddlGenre.SelectedValue;
                editedContact.email          = txtEmail.Text;
                editedContact.mobileNumber   = txtMobileNumber.Text;
                editedContact.landlineNumber = txtLandlineNumber.Text;
                editedContact.picExtension   = fileExtension;
                editedContact.comments       = txtComments.Text;

                result = contactsService.editContact(editedContact, chkDeletePic.Checked);
                if (result.code == TransactionResultDTO.transactionResultCode.Success)
                {
                    try
                    {
                        if (uplContactPic.HasFile)
                        {
                            uplContactPic.SaveAs(Server.MapPath(SitePaths.contactsPics(SessionManager.sessionMemberInfo.id) + Encoding.sha1(editedContact.id.ToString()) + fileExtension));
                        }

                        Response.Redirect(Pages.getContactsDefault(), false);
                    }
                    catch (Exception)
                    {
                        showError(HttpContext.GetGlobalResourceObject("Resource", "ErrorGeneral").ToString());
                    }
                }
                else
                {
                    showError(result.failureReason);
                }
            }
            catch (Exception)
            {
                showError(HttpContext.GetGlobalResourceObject("Resource", "ErrorGeneral").ToString());
            }
        }
Esempio n. 40
0
 /// <summary>
 /// Update the culture cookie
 /// </summary>
 public void UpdateCultureCookie(HttpContext context, string culture)
 {
     context.Response.Cookies.Append(
         CookieRequestCultureProvider.DefaultCookieName,
         CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)));
 }
Esempio n. 41
0
        public async Task<IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they 
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);
                    
                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return Redirect(model.ReturnUrl);
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return Redirect("~/");
                }
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Username);

                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

                    // only set explicit expiration here if user chooses "remember me". 
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    };

                    var isuser = new IdentityServerUser(user.Id)
                    {
                        DisplayName = user.UserName,
                        AdditionalClaims = new List<Claim>
                        {
                            new Claim("AspNet.Identity.SecurityStamp", user.SecurityStamp)
                        }
                    };

                    // issue authentication cookie with subject ID and username
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));
                    await HttpContext.SignInAsync(isuser, props);

                    // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return Redirect(model.ReturnUrl);
                    }

                    return Redirect("~/");
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await _account.BuildLoginViewModelAsync(model);
            return View(vm);
        }
 public AuthenticationFailedContext(HttpContext context, OpenIdConnectOptions options)
     : base(context, options)
 {
 }
Esempio n. 43
0
        public async Task <IActionResult> LogoutAsync()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return(Ok(true));
        }
 public static bool IsAuthenticated(this HttpContext context)
 {
     return(context.User.Identity != null && context.User.Identity.IsAuthenticated);
 }
Esempio n. 45
0
 private HttpContextServerCallContext CreateServerCallContext(HttpContext httpContext, ILogger?logger = null)
 {
     return(new HttpContextServerCallContext(httpContext, new GrpcServiceOptions(), logger ?? NullLogger.Instance));
 }
Esempio n. 46
0
 public HttpContextAdapter()
 {
     this._httpContext = HttpContext.Current;
 }
        public async Task <IActionResult> GetUserEquipmentForUser([FromQuery] Guid userId)
        {
            var equipments = await _equipmentService.GetUserEquipmentForUserAsync(HttpContext.GetUser(), userId);

            return(Ok(GetRequestResult(equipments)));
        }
Esempio n. 48
0
 public ListFileManager(HttpContext context, string pathToList, string[] searchExtensions)
     : base(context)
 {
     this.SearchExtensions = searchExtensions.Select(x => x.ToLower()).ToArray();
     this.PathToList       = pathToList;
 }
 public async Task <IActionResult> Get([FromQuery] long Id)
 {
     return(Ok(GetRequestResult(await _equipmentService.GetAsync(HttpContext.GetUser(), Id))));
 }
        public async Task <IActionResult> AddEquipmentAttachment([FromBody] AddEquipmentAttachmentFormModel equipmentAttachmentForm)
        {
            var equipments = await _equipmentService.AddEquipmentAttachmentAsync(HttpContext.GetUser(), equipmentAttachmentForm);

            return(Ok(GetRequestResult(equipments)));
        }
Esempio n. 51
0
 public static void ImportProducts(DataTable productData, int categoryId, int lineId, int? brandId, ProductSaleStatus saleStatus, bool isImportFromTaobao,string wid)
 {
     if ((productData != null) && (productData.Rows.Count > 0))
     {
         foreach (DataRow row in productData.Rows)
         {
             ProductInfo product = new ProductInfo {
                 CategoryId = categoryId,
                 MainCategoryPath = CatalogHelper.GetCategory(categoryId).Path + "|",
                 ProductName = (string) row["ProductName"],
                 ProductCode = (string) row["SKU"],
                 BrandId = brandId
             };
             if (row["Description"] != DBNull.Value)
             {
                 product.Description = (string) row["Description"];
             }
             product.MarketPrice = new decimal?((decimal) row["SalePrice"]);
             product.AddedDate = DateTime.Now;
             product.SaleStatus = saleStatus;
             product.HasSKU = false;
             HttpContext current = HttpContext.Current;
             if (row["ImageUrl1"] != DBNull.Value)
             {
                 product.ImageUrl1 = (string) row["ImageUrl1"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl1) && (product.ImageUrl1.Length > 0))
             {
                 string[] strArray = ProcessImages(current, product.ImageUrl1);
                 product.ThumbnailUrl40 = strArray[0];
                 product.ThumbnailUrl60 = strArray[1];
                 product.ThumbnailUrl100 = strArray[2];
                 product.ThumbnailUrl160 = strArray[3];
                 product.ThumbnailUrl180 = strArray[4];
                 product.ThumbnailUrl220 = strArray[5];
                 product.ThumbnailUrl310 = strArray[6];
                 product.ThumbnailUrl410 = strArray[7];
             }
             if (row["ImageUrl2"] != DBNull.Value)
             {
                 product.ImageUrl2 = (string) row["ImageUrl2"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl2) && (product.ImageUrl2.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl2);
             }
             if (row["ImageUrl3"] != DBNull.Value)
             {
                 product.ImageUrl3 = (string) row["ImageUrl3"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl3) && (product.ImageUrl3.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl3);
             }
             if (row["ImageUrl4"] != DBNull.Value)
             {
                 product.ImageUrl4 = (string) row["ImageUrl4"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl4) && (product.ImageUrl4.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl4);
             }
             if (row["ImageUrl5"] != DBNull.Value)
             {
                 product.ImageUrl5 = (string) row["ImageUrl5"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl5) && (product.ImageUrl5.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl5);
             }
             SKUItem item = new SKUItem {
                 SkuId = "0",
                 SKU = (string) row["SKU"]
             };
             if (row["Stock"] != DBNull.Value)
             {
                 item.Stock = (int) row["Stock"];
             }
             if (row["Weight"] != DBNull.Value)
             {
                 item.Weight = (decimal) row["Weight"];
             }
             item.SalePrice = (decimal) row["SalePrice"];
             Dictionary<string, SKUItem> skus = new Dictionary<string, SKUItem>();
             skus.Add(item.SkuId, item);
             ProductActionStatus status = AddProduct(product, skus, null, null,wid);
             if (isImportFromTaobao && (status == ProductActionStatus.Success))
             {
                 TaobaoProductInfo taobaoProduct = new TaobaoProductInfo {
                     ProductId = product.ProductId,
                     ProTitle = product.ProductName,
                     Cid = (long) row["Cid"]
                 };
                 if (row["StuffStatus"] != DBNull.Value)
                 {
                     taobaoProduct.StuffStatus = (string) row["StuffStatus"];
                 }
                 taobaoProduct.Num = (long) row["Num"];
                 taobaoProduct.LocationState = (string) row["LocationState"];
                 taobaoProduct.LocationCity = (string) row["LocationCity"];
                 taobaoProduct.FreightPayer = (string) row["FreightPayer"];
                 if (row["PostFee"] != DBNull.Value)
                 {
                     taobaoProduct.PostFee = (decimal) row["PostFee"];
                 }
                 if (row["ExpressFee"] != DBNull.Value)
                 {
                     taobaoProduct.ExpressFee = (decimal) row["ExpressFee"];
                 }
                 if (row["EMSFee"] != DBNull.Value)
                 {
                     taobaoProduct.EMSFee = (decimal) row["EMSFee"];
                 }
                 taobaoProduct.HasInvoice = (bool) row["HasInvoice"];
                 taobaoProduct.HasWarranty = (bool) row["HasWarranty"];
                 taobaoProduct.HasDiscount = (bool) row["HasDiscount"];
                 taobaoProduct.ValidThru = (long) row["ValidThru"];
                 if (row["ListTime"] != DBNull.Value)
                 {
                     taobaoProduct.ListTime = (DateTime) row["ListTime"];
                 }
                 else
                 {
                     taobaoProduct.ListTime = DateTime.Now;
                 }
                 if (row["PropertyAlias"] != DBNull.Value)
                 {
                     taobaoProduct.PropertyAlias = (string) row["PropertyAlias"];
                 }
                 if (row["InputPids"] != DBNull.Value)
                 {
                     taobaoProduct.InputPids = (string) row["InputPids"];
                 }
                 if (row["InputStr"] != DBNull.Value)
                 {
                     taobaoProduct.InputStr = (string) row["InputStr"];
                 }
                 if (row["SkuProperties"] != DBNull.Value)
                 {
                     taobaoProduct.SkuProperties = (string) row["SkuProperties"];
                 }
                 if (row["SkuQuantities"] != DBNull.Value)
                 {
                     taobaoProduct.SkuQuantities = (string) row["SkuQuantities"];
                 }
                 if (row["SkuPrices"] != DBNull.Value)
                 {
                     taobaoProduct.SkuPrices = (string) row["SkuPrices"];
                 }
                 if (row["SkuOuterIds"] != DBNull.Value)
                 {
                     taobaoProduct.SkuOuterIds = (string) row["SkuOuterIds"];
                 }
                 UpdateToaobProduct(taobaoProduct);
             }
         }
     }
 }
        public async Task <IActionResult> GetEquipmentByUser()
        {
            var equipments = await _equipmentService.GetEquipmentByUserAsync(HttpContext.GetUser());

            return(Ok(GetRequestResult(equipments)));
        }
Esempio n. 53
0
 /// <summary>
 /// Handles the actual HTTP request
 /// </summary>
 /// <param name="httpContext"></param>
 /// <param name="segments"></param>
 /// <returns></returns>
 public abstract Task Handle(HttpContext httpContext, string[] segments);
        public async Task <IActionResult> GetEquipmentAttachmentForUser([FromBody] EquipmentAttachmentUserFormModel equipmentAttachmentUserFormModel)
        {
            var equipmentAtts = await _equipmentService.GetEquipmentAttachmentForUserAsync(HttpContext.GetUser(), equipmentAttachmentUserFormModel);

            return(Ok(GetRequestResult(equipmentAtts)));
        }
Esempio n. 55
0
 public AccountUtil(HttpContext Context)
 {
     context = Context;
     manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
     roleManager = Context.GetOwinContext().GetUserManager<ApplicationRoleManager>();
 }
Esempio n. 56
0
 private void EndInvoke(HttpContext context)
 {
     _experimentService.SaveExperiments(Experiments);
 }
Esempio n. 57
0
 /// <summary>
 /// 页面功能实体
 /// </summary>
 /// <param name="mycontext"></param>
 public WF_Admin_Sln(HttpContext mycontext)
 {
     this.context = mycontext;
 }
Esempio n. 58
0
        public async Task <IActionResult> GetSummary([FromRoute] Guid carId, [FromQuery] GetSummaryQueryRequest request)
        {
            var result = await _summaryService.GetSummaryByCarIdAsync(carId, HttpContext.GetUserId(), request.StartDate, request.EndDate);

            return(GenerateResponse(result));
        }
Esempio n. 59
0
 public abstract void ProcessRequest(HttpContext context);
 public IActionResult Logout()
 {
     HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
     return(RedirectToAction("Login"));
 }