public MvcForm(HttpResponseBase httpResponse) { if (httpResponse == null) { throw new ArgumentNullException("httpResponse"); } _writer = httpResponse.Output; }
internal static void DeleteAuthCookie(HttpResponseBase response) { // Expire the cookie var cookie = new HttpCookie(AuthCookieName); cookie.Expires = DateTime.Now.AddDays(-1); response.Cookies.Add(cookie); }
internal void ProcessRequest(HttpResponseBase response) { string virtualPath = _path; // Make sure it starts with ~/ if (!virtualPath.StartsWith("~/", StringComparison.Ordinal)) { virtualPath = "~/" + virtualPath; } // Get the resource stream for this virtual path using (var stream = _applicationPart.GetResourceStream(virtualPath)) { if (stream == null) { throw new HttpException(404, String.Format( CultureInfo.CurrentCulture, WebPageResources.ApplicationPart_ResourceNotFound, _path)); } // Set the mime type based on the file extension response.ContentType = MimeMapping.GetMimeMapping(virtualPath); // Copy it to the response stream.CopyTo(response.OutputStream); } }
public MvcForm(HttpResponseBase httpResponse) { if (httpResponse == null) { throw new ArgumentNullException("httpResponse"); } _httpResponse = httpResponse; }
internal static void SetAuthCookie(HttpResponseBase response) { // Get an auth admin cookie HttpCookie cookie = GetAuthCookie(); // Set the name to our auth cookie name cookie.Name = AuthCookieName; // Add it to the response response.Cookies.Add(cookie); }
internal MvcForm(ViewContext viewContext) { if (viewContext == null) { throw new ArgumentNullException("viewContext"); } _viewContext = viewContext; _httpResponse = viewContext.HttpContext.Response; // push the new FormContext _originalFormContext = viewContext.FormContext; viewContext.FormContext = new FormContext(); }
internal static void PersistFilter(HttpResponseBase response, string cookieName, IDictionary<string, string> filterItems) { var cookie = response.Cookies[cookieName]; if (cookie == null) { cookie = new HttpCookie(cookieName); response.Cookies.Add(cookie); } foreach (var item in filterItems) { cookie[item.Key] = item.Value; } }
public static Mock<HttpContextBase> CreateTestContext(HttpRequestBase request = null, HttpResponseBase response = null, IDictionary items = null) { items = items ?? new Hashtable(); request = request ?? CreateTestRequest("default.cshtml", "http://localhost/default.cshtml").Object; if (response == null) { var mockResponse = new Mock<HttpResponseBase>(); mockResponse.Setup(r => r.Cookies).Returns(new HttpCookieCollection()); response = mockResponse.Object; } var httpContext = new Mock<HttpContextBase>(); httpContext.SetupGet(c => c.Items).Returns(items); httpContext.SetupGet(c => c.Request).Returns(request); httpContext.SetupGet(c => c.Response).Returns(response); return httpContext; }
private static void OutputClientValidation(HttpResponseBase response, FormContext formContext) { if (!formContext.ClientValidationEnabled) { return; // do nothing } // output a call that resembles: // _clientValidationFunction(validationObject, userContext); string validationJson = formContext.GetJsonValidationMetadata(); string userContextJson = (formContext.ClientValidationState != null) ? new JavaScriptSerializer().Serialize(formContext.ClientValidationState) : "null"; string scriptWithCorrectNewLines = _clientValidationScript.Replace("\r\n", Environment.NewLine); string formatted = String.Format(CultureInfo.InvariantCulture, scriptWithCorrectNewLines, formContext.ClientValidationFunction, validationJson, userContextJson); response.Write(formatted); }
protected override void WriteFile(HttpResponseBase response) { // grab chunks of data and write to the output stream Stream outputStream = response.OutputStream; using (FileStream) { byte[] buffer = new byte[BufferSize]; while (true) { int bytesRead = FileStream.Read(buffer, 0, BufferSize); if (bytesRead == 0) { // no more data break; } outputStream.Write(buffer, 0, bytesRead); } } }
public async Task <AuthenticateResult> AuthenticateAsync(HttpRequestBase request, HttpResponseBase response) { request.ThrowIfNull("request"); response.ThrowIfNull("response"); if (_authenticationProvider == null) { return(AuthenticateResult.NoAuthenticationPerformed()); } AuthenticationResult result = await _authenticationProvider.AuthenticateAsync(request, response, this); return(result == AuthenticationResult.AuthenticationSucceeded ? AuthenticateResult.AuthenticationSucceeded() : AuthenticateResult.AuthenticationFailed(await _authenticationProvider.GetFailedAuthenticationResponseAsync(request))); }
private static HttpContextBase CreateStubContext(HttpRequestBase request, HttpResponseBase response) { Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(); contextMock.SetupGet(m => m.Request).Returns(request); contextMock.SetupGet(m => m.Response).Returns(response); return contextMock.Object; }
private static HttpContextBase CreateStubContextBase(HttpResponseBase response) { return CreateStubContextBase(request: null, response: response); }
private void AddResponseFilter(HttpResponseBase response, Func<Stream, Stream> factory) { _original = response.Filter; response.Filter = factory(response.Filter); }
private static void AbortConnection(HttpResponseBase httpResponseBase) { // TODO: DevDiv bug #381233 -- call HttpResponse.Abort when it becomes available in 4.5 httpResponseBase.Close(); }
internal static async Task WriteStreamedResponseContentAsync(HttpResponseBase httpResponseBase, HttpContent responseContent) { Contract.Assert(httpResponseBase != null); Contract.Assert(responseContent != null); try { // Copy the HttpContent into the output stream asynchronously. await responseContent.CopyToAsync(httpResponseBase.OutputStream); } catch { // Streamed content may have been written and cannot be recalled. // Our only choice is to abort the connection. AbortConnection(httpResponseBase); } }
private static async Task WriteErrorResponseContentAsync(HttpResponseBase httpResponseBase, HttpRequestMessage request, HttpResponseMessage errorResponse, CancellationToken cancellationToken, IExceptionLogger exceptionLogger) { HttpRequestMessage ignoreUnused = request; try { Exception exception = null; cancellationToken.ThrowIfCancellationRequested(); try { // Asynchronously write the content of the new error HttpResponseMessage await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream); return; } catch (Exception ex) { exception = ex; } Contract.Assert(exception != null); ExceptionContext exceptionContext = new ExceptionContext(exception, WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError, request, errorResponse); await exceptionLogger.LogAsync(exceptionContext, cancellationToken); // Failure writing the error response. Likely cause is a formatter // serialization exception. Create empty error response and // return a non-faulted task. SetEmptyErrorResponse(httpResponseBase); } finally { // Dispose the temporary HttpResponseMessage carrying the error response errorResponse.Dispose(); } }
public void GenerarPlanillaDespacho(int idPedido, HttpResponseBase response) { var localReport = GetReportePlanillaDespacho(idPedido); ProcesadorReporte.GenerarWord(localReport, "PlanillaDespacho", response); }
public void GenerarInformeServicioBasico(long fechaDesde, long fechaHasta, HttpResponseBase response) { var localReport = GetInformeServicioBasico(fechaDesde, fechaHasta); ProcesadorReporte.GenerarWord(localReport, "ServiciosBasicos", response); }
public static HttpCookie cookie(this HttpResponseBase response, string cookieName, string cookieValue) { return(response.set_Cookie(cookieName, cookieValue)); }
public void GenerarRecibiConforme(int idPedido, HttpResponseBase response) { var localReport = GetReporteRecibiConforme(idPedido); ProcesadorReporte.GenerarWord(localReport, "RecibiConforme", response); }
public static bool hasCookie(this HttpResponseBase response, string cookieName) { return(response.notNull() && response.Cookies.notNull() && response.Cookies[cookieName].notNull()); }
public abstract void SendResponse(HttpResponseBase response);
public static void AuthenticateRequest(HttpContextBase context, bool allowUnknownExtensinons) { HttpRequestBase request = context.Request; HttpResponseBase response = context.Response; //First check if we are upgrading/installing if (request == null || request.Url == null || request.Url.LocalPath.ToLower().EndsWith("install.aspx") || request.Url.LocalPath.ToLower().Contains("upgradewizard.aspx") || request.Url.LocalPath.ToLower().Contains("installwizard.aspx")) { return; } //exit if a request for a .net mapping that isn't a content page is made i.e. axd if (allowUnknownExtensinons == false && request.Url.LocalPath.ToLower().EndsWith(".aspx") == false && request.Url.LocalPath.ToLower().EndsWith(".asmx") == false && request.Url.LocalPath.ToLower().EndsWith(".ashx") == false) { return; } //Obtain PortalSettings from Current Context PortalSettings portalSettings = PortalController.GetCurrentPortalSettings(); bool isActiveDirectoryAuthHeaderPresent = false; var auth = request.Headers.Get("Authorization"); if (!string.IsNullOrEmpty(auth)) { if (auth.StartsWith("Negotiate")) { isActiveDirectoryAuthHeaderPresent = true; } } if (request.IsAuthenticated && !isActiveDirectoryAuthHeaderPresent && portalSettings != null) { var roleController = new RoleController(); var user = UserController.GetCachedUser(portalSettings.PortalId, context.User.Identity.Name); //if current login is from windows authentication, the ignore the process if (user == null && context.User is WindowsPrincipal) { return; } //authenticate user and set last login ( this is necessary for users who have a permanent Auth cookie set ) if (user == null || user.IsDeleted || user.Membership.LockedOut || (!user.Membership.Approved && !user.IsInRole("Unverified Users")) || user.Username.ToLower() != context.User.Identity.Name.ToLower()) { var portalSecurity = new PortalSecurity(); portalSecurity.SignOut(); //Remove user from cache if (user != null) { DataCache.ClearUserCache(portalSettings.PortalId, context.User.Identity.Name); } //Redirect browser back to home page response.Redirect(request.RawUrl, true); return; } if (!user.IsSuperUser && user.IsInRole("Unverified Users") && !HttpContext.Current.Items.Contains(DotNetNuke.UI.Skins.Skin.OnInitMessage)) { HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessage, Localization.GetString("UnverifiedUser", Localization.SharedResourceFile, CurrentCulture)); } if (!user.IsSuperUser && HttpContext.Current.Request.QueryString.AllKeys.Contains("VerificationSuccess") && !HttpContext.Current.Items.Contains(DotNetNuke.UI.Skins.Skin.OnInitMessage)) { HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessage, Localization.GetString("VerificationSuccess", Localization.SharedResourceFile, CurrentCulture)); HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessageType, ModuleMessage.ModuleMessageType.GreenSuccess); } //if users LastActivityDate is outside of the UsersOnlineTimeWindow then record user activity if (DateTime.Compare(user.Membership.LastActivityDate.AddMinutes(Host.UsersOnlineTimeWindow), DateTime.Now) < 0) { //update LastActivityDate and IP Address for user user.Membership.LastActivityDate = DateTime.Now; user.LastIPAddress = request.UserHostAddress; UserController.UpdateUser(portalSettings.PortalId, user, false, false); } //check for RSVP code if (request.QueryString["rsvp"] != null && !string.IsNullOrEmpty(request.QueryString["rsvp"])) { foreach (var role in TestableRoleController.Instance.GetRoles(portalSettings.PortalId, r => (r.SecurityMode != SecurityMode.SocialGroup || r.IsPublic) && r.Status == RoleStatus.Approved)) { if (role.RSVPCode == request.QueryString["rsvp"]) { roleController.UpdateUserRole(portalSettings.PortalId, user.UserID, role.RoleID); } } } //save userinfo object in context context.Items.Add("UserInfo", user); //Localization.SetLanguage also updates the user profile, so this needs to go after the profile is loaded Localization.SetLanguage(user.Profile.PreferredLocale); } if (context.Items["UserInfo"] == null) { context.Items.Add("UserInfo", new UserInfo()); } }
protected abstract void WriteFile(HttpResponseBase response);
public void SendConfirmationEmail(string email, HttpRequestBase request, HttpResponseBase response) { if (String.IsNullOrEmpty(email)) { throw new ArgumentNullException("email"); } MailAddress from = new MailAddress("*****@*****.**"); try { from = new MailAddress(this.Config.AdminEmail); } catch { } MailAddress to; try { to = new MailAddress(email); } catch { return; } using (var message = new MailMessage(from, to)) { String body = this.Config.ConfirmEmailText; String subject = this.Config.ConfirmEmailSubject; EmailConfirm confirm = new EmailConfirm { Email = email, Key = Guid.NewGuid() }; this.Db.EmailConfirms.InsertOnSubmit(confirm); this.Db.SubmitChanges(); String Link = request.Url.Scheme + Uri.SchemeDelimiter + request.Url.Authority + response.ApplyAppPathModifier("~/Account/Confirm?key=" + confirm.Key); try { message.Subject = subject; message.Body = String.Format(body, Link); message.IsBodyHtml = true; } catch (FormatException) { return; } try { using (var client = new SmtpClient(this.Config.SmtpHost, this.Config.SmtpPort)) { client.Send(message); } } catch { } } }
/// <summary> /// Handles the upgrade /// </summary> /// <param name="source">Channel that we've received a request from</param> /// <param name="msg">Message received.</param> protected override void OnMessage(ITcpChannel source, object msg) { var httpMessage = msg as IHttpMessage; if (WebSocketUtils.IsWebSocketUpgrade(httpMessage)) { if (httpMessage is IHttpRequest) // server mode { var args = new WebSocketClientConnectEventArgs(source, (IHttpRequest) httpMessage); WebSocketClientConnect(this, args); if (args.MayConnect) { var webSocketKey = httpMessage.Headers["Sec-WebSocket-Key"]; // TODO: why not provide the response in the WebSocketClientConnectEventArgs event? var response = new WebSocketUpgradeResponse(webSocketKey); source.Send(response); WebSocketClientConnected(this, new WebSocketClientConnectedEventArgs(source, (IHttpRequest) httpMessage, response)); } else if (args.SendResponse) { var response = new HttpResponseBase(HttpStatusCode.NotImplemented, "Not Implemented", "HTTP/1.1"); if (args.Response != null) response.Body = args.Response; source.Send(response); } return; } if (httpMessage is IHttpResponse) // client mode { WebSocketClientConnected(this, new WebSocketClientConnectedEventArgs(source, null, (IHttpResponse) httpMessage)); } } var webSocketMessage = msg as IWebSocketMessage; if (webSocketMessage != null) { // standard message responses handled by listener switch (webSocketMessage.Opcode) { case WebSocketOpcode.Ping: source.Send(new WebSocketMessage(WebSocketOpcode.Pong, webSocketMessage.Payload)); return; case WebSocketOpcode.Close: source.Send(new WebSocketMessage(WebSocketOpcode.Close)); source.Close(); WebSocketClientDisconnected(this, new ClientDisconnectedEventArgs(source, new Exception("WebSocket closed"))); return; } _webSocketMessageReceived(source, webSocketMessage); return; } base.OnMessage(source, msg); }
protected User Register(string username, string password, string email, string question, string answer, char gender, bool showEmail, bool showGender, HttpRequestBase request, HttpResponseBase response) { var validEmail = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"); var whiteSpace = new Regex(@"\s"); if (string.IsNullOrEmpty(username)) { throw new ArgumentException("Your username must not be blank."); } if (string.IsNullOrEmpty(password) || password.Length < 5) { throw new ArgumentException("Your password must be at least five characters."); } if (string.IsNullOrEmpty(email) || !validEmail.IsMatch(email)) { throw new ArgumentException("The email you entered is invalid."); } if (string.IsNullOrEmpty(question) || question.Length < 3) { throw new ArgumentException("Your security question must be at least three characters."); } if (string.IsNullOrEmpty(answer) || answer.Length < 3) { throw new ArgumentException("Your security answer must be at least three characters."); } if (!gender.Equals('M') && !gender.Equals('F')) { throw new ArgumentException("Your gender must be 'M' or 'F'."); } if (whiteSpace.IsMatch(username)) { throw new ArgumentException("Your username may not contain any whitespace."); } if (username.Contains("[") || username.Contains("]")) { throw new ArgumentException("Your username may not contain square brackets. (They will interfere with BBCode.)"); } var passwordHash = ComputeHash(password); var existingUsers = from u in this.Db.Users where u.Username == username || u.Email == email select u; if (existingUsers.Count() > 0) { throw new UserAlreadyRegisteredException("There is already a user registered using that username or email address."); } var totalUsers = this.Db.Users.Count(); var newUser = new User { Username = username, PasswordHash = passwordHash, Email = email, SecurityQuestion = question, SecurityAnswer = answer, Gender = gender, ShowEmail = showEmail, ShowGender = showGender, IsEmailConfirmed = false, CreateDate = DateTime.UtcNow, ReceiveAdminEmail = true, }; if (!newUser.IsValid) { throw new InvalidOperationException("Blah!"); } this.Db.Users.InsertOnSubmit(newUser); foreach (var role in from r in this.Db.Roles where r.IsDefault || (totalUsers == 0 && r.IsAdministrator) select r) { this.Db.UsersRoles.InsertOnSubmit(new UsersRole { User = newUser, Role = role }); } this.Db.SubmitChanges(); this.SendConfirmationEmail(email, request, response); return(newUser); }
private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase) { httpResponseBase.Clear(); httpResponseBase.ClearHeaders(); }
public void SetResponse(HttpResponseBase response) { _response = response; }
private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase) { httpResponseBase.Clear(); // Despite what the documentation indicates, calling Clear on its own doesn't fully clear the headers. httpResponseBase.ClearHeaders(); }
internal DisconnectWatcher(HttpResponseBase httpResponse) { _httpResponse = httpResponse; }
private void AddCrossOriginAccessHeaders(HttpResponseBase response) { response.Headers["Access-Control-Allow-Headers"] = "*"; response.Headers["Access-Control-Allow-Origin"] = "*"; }
public void ServeRequest(HttpRequestBase request, HttpResponseBase response, IEntityResponder entityResponder) { if (!IsHttpMethodAllowed(request)) { //If we are unable to parse url send 405 Method not allowed HttpResponseHeaderHelper.SendHttpStatusHeaders(response, HttpStatusCode.MethodNotAllowed); return; } if (!entityResponder.IsAllowedToServeRequestedEntity) { //If we are unable to parse url send 403 Path Forbidden HttpResponseHeaderHelper.SendHttpStatusHeaders(response, HttpStatusCode.Forbidden); return; } var requestHttpMethod = HttpRequestHeaderHelper.GetHttpMethod(request); var compressionType = HttpRequestHeaderHelper.GetCompressionMode(request); // If this is a binary file like image, then we won't compress it. if (!entityResponder.IsCompressable) { compressionType = ResponseCompressionType.None; } // If it is a partial request we need to get bytes of orginal entity data, we will compress the byte ranges returned var entityStoredWithCompressionType = compressionType; var isRangeRequest = HttpRequestHeaderHelper.IsRangeRequest(request); if (isRangeRequest) { entityStoredWithCompressionType = ResponseCompressionType.None; } EntityCacheItem fileEntityCacheItem = null; if (!entityResponder.TryGetFileHandlerCacheItem(entityStoredWithCompressionType, out fileEntityCacheItem)) { //File does not exist if (!entityResponder.DoesEntityExists) { HttpResponseHeaderHelper.SendHttpStatusHeaders(response, HttpStatusCode.NotFound); return; } //File too large to send if (entityResponder.IsEntityLargerThanMaxFileSize) { HttpResponseHeaderHelper.SendHttpStatusHeaders(response, HttpStatusCode.RequestEntityTooLarge); return; } } else if (fileEntityCacheItem.EntityData == null && !entityResponder.DoesEntityExists) { //If we have cached the properties of the file but its to large to serve from memory then we must check that the file exists each time. HttpResponseHeaderHelper.SendHttpStatusHeaders(response, HttpStatusCode.NotFound); return; } //Unable to parse request range header IEnumerable <RangeItem> ranges = null; var requestRange = HttpRequestHeaderHelper.GetRanges(request, fileEntityCacheItem.ContentLength, out ranges); if (requestRange.HasValue && !requestRange.Value) { HttpResponseHeaderHelper.SendHttpStatusHeaders(response, HttpStatusCode.RequestedRangeNotSatisfiable); return; } //Check querystring etag var urlEtagHandler = GetUrlEtagHandler(request, response, entityResponder.UrlEtagHandlingMethod, entityResponder.UrlEtagQuerystringName, fileEntityCacheItem.Etag); if (urlEtagHandler != null) { var shouldStopResponse = urlEtagHandler.UpdateEtag(response, request.Url, fileEntityCacheItem.Etag); if (shouldStopResponse) { return; } } //Check if cached response is valid and if it is send appropriate response headers var httpStatus = GetResponseHttpStatus(request, fileEntityCacheItem.LastModified, fileEntityCacheItem.Etag); HttpResponseHeaderHelper.SendHttpStatusHeaders(response, httpStatus); if (httpStatus == HttpStatusCode.NotModified || httpStatus == HttpStatusCode.PreconditionFailed) { return; } //Tell the client it supports resumable requests HttpResponseHeaderHelper.SetResponseResumable(response); //How the entity should be cached on the client HttpResponseHeaderHelper.SetResponseCachable(response, DateTime.Now, fileEntityCacheItem.LastModified, fileEntityCacheItem.Etag, entityResponder.Expires); var entityResponseForEntity = GetEntityResponse(response, ranges); entityResponseForEntity.SendHeaders(response, compressionType, fileEntityCacheItem); var transmitEntity = entityResponder.GetTransmitEntityStrategy(fileEntityCacheItem); entityResponseForEntity.SendBody(requestHttpMethod, response, transmitEntity); }
private static void CreateEmptyErrorResponse(HttpResponseBase httpResponseBase) { ClearContentAndHeaders(httpResponseBase); httpResponseBase.StatusCode = (int)HttpStatusCode.InternalServerError; httpResponseBase.SuppressContent = true; }
protected override void WriteFile(HttpResponseBase response) { response.TransmitFile(FileName); }
internal static Task WriteStreamedResponseContentAsync(HttpResponseBase httpResponseBase, HttpContent responseContent) { Contract.Assert(httpResponseBase != null); Contract.Assert(responseContent != null); Task writeResponseContentTask = null; try { // Copy the HttpContent into the output stream asynchronously. writeResponseContentTask = responseContent.CopyToAsync(httpResponseBase.OutputStream); } catch { // Streamed content may have been written and cannot be recalled. // Our only choice is to abort the connection. AbortConnection(httpResponseBase); return TaskHelpers.Completed(); } return writeResponseContentTask .Catch((info) => { // Streamed content may have been written and cannot be recalled. // Our only choice is to abort the connection. AbortConnection(httpResponseBase); return info.Handled(); }); }
protected override void WriteFile(HttpResponseBase response) { WasWriteFileCalled = true; }
/// <summary> /// Writes the entire file to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> protected override void WriteEntireEntity(HttpResponseBase response) { response.TransmitFile(FileName); }
private static string ResponseSummary(ExceptionContext filterContext) { if (filterContext.HttpContext == null) { return("HttpContext is null"); } if (filterContext.HttpContext.Response == null) { return("HttpContext.Reponse is null"); } StringBuilder responseSummary = new StringBuilder(); HttpResponseBase response = filterContext.HttpContext.Response; try { responseSummary.AppendFormat("\tIsClientConnected: {0}{1}", response.IsClientConnected, Environment.NewLine); responseSummary.AppendFormat("\tBufferOutput: {0}{1}", response.BufferOutput, Environment.NewLine); responseSummary.AppendFormat("\tIsRequestBeingRedirected: {0}{1}", response.IsRequestBeingRedirected, Environment.NewLine); responseSummary.AppendFormat("\tStatus: {0}{1}", response.Status, Environment.NewLine); responseSummary.AppendFormat("\tStatusCode: {0}{1}", response.StatusCode, Environment.NewLine); } catch (Exception exception) { responseSummary.AppendFormat("{0}{0}Exception listing response properties: {1}", Environment.NewLine, exception.ToString()); } try { if (response.Cookies != null) { responseSummary.AppendLine("\tCookies:"); foreach (string key in response.Cookies.AllKeys) { HttpCookie cookie = response.Cookies[key]; // Cookie values are obmitted so that information like RPS tickets isn't written to the logs (we do the same thing with request cookies) responseSummary.AppendFormat("\t\tName={0}: Expires={1}, Domain={2}, HttpOnly={3}, Path={4}, Secure={5} Value=[Redacted] ({6} characters){7}", key, cookie.Expires.ToString(CultureInfo.InvariantCulture), cookie.Domain, cookie.HttpOnly, cookie.Path, cookie.Secure, (cookie.Value ?? string.Empty).Length, Environment.NewLine); } } } catch (Exception exception) { responseSummary.AppendFormat("{0}{0}Exception listing response cookies: {1}", Environment.NewLine, exception.ToString()); } try { if (response.Headers != null) { responseSummary.AppendLine("\tHeaders:"); foreach (string key in response.Headers.AllKeys) { responseSummary.AppendFormat("\t\t{0} = {1} ({2} characters) {3}", key, key == "Set-Cookie" ? "[Redacted]" : response.Headers[key], (response.Headers[key] ?? string.Empty).Length, Environment.NewLine); } } } catch (Exception exception) { responseSummary.AppendFormat("{0}{0}Exception listing response headers: {1}", Environment.NewLine, exception.ToString()); } return(responseSummary.ToString()); }
/// <summary> /// Writes the file range to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> /// <param name="rangeStartIndex">Range start index</param> /// <param name="rangeEndIndex">Range end index</param> protected override void WriteEntityRange(HttpResponseBase response, long rangeStartIndex, long rangeEndIndex) { response.TransmitFile(FileName, rangeStartIndex, (rangeEndIndex - rangeStartIndex) + 1); }
internal static Task CreateErrorResponseAsync(HttpContextBase httpContextBase, HttpContent responseContent, HttpRequestMessage request, Exception exception) { Contract.Assert(httpContextBase != null); Contract.Assert(responseContent != null); Contract.Assert(exception != null); Contract.Assert(request != null); HttpResponseBase httpResponseBase = httpContextBase.Response; HttpResponseMessage errorResponse = null; HttpResponseException responseException = exception as HttpResponseException; // Ensure all headers and content are cleared to eliminate any partial results. ClearContentAndHeaders(httpResponseBase); // If the exception we are handling is HttpResponseException, // that becomes the error response. if (responseException != null) { errorResponse = responseException.Response; } else { // The exception is not HttpResponseException. // Create a 500 response with content containing an explanatory message and // stack trace, subject to content negotiation and policy for error details. try { MediaTypeHeaderValue mediaType = responseContent.Headers.ContentType; string messageDetails = (mediaType != null) ? Error.Format( SRResources.Serialize_Response_Failed_MediaType, responseContent.GetType().Name, mediaType) : Error.Format( SRResources.Serialize_Response_Failed, responseContent.GetType().Name); errorResponse = request.CreateErrorResponse( HttpStatusCode.InternalServerError, new InvalidOperationException(messageDetails, exception)); // CreateErrorResponse will choose 406 if it cannot find a formatter, // but we want our default error response to be 500 always errorResponse.StatusCode = HttpStatusCode.InternalServerError; } catch { // Failed creating an HttpResponseMessage for the error response. // This can happen for missing config, missing conneg service, etc. // Create an empty error response and return a non-faulted task. CreateEmptyErrorResponse(httpResponseBase); return(TaskHelpers.Completed()); } } Contract.Assert(errorResponse != null); CopyResponseStatusAndHeaders(httpContextBase, errorResponse); // The error response may return a null content if content negotiation // fails to find a formatter, or this may be an HttpResponseException without // content. In either case, cleanup and return a completed task. if (errorResponse.Content == null) { errorResponse.Dispose(); return(TaskHelpers.Completed()); } // Copy the headers from the newly generated HttpResponseMessage. // We must ask the content for its content length because Content-Length // is lazily computed and added to the headers. var unused = errorResponse.Content.Headers.ContentLength; CopyHeaders(errorResponse.Content.Headers, httpContextBase); Task writeErrorResponseTask = null; try { // Asynchronously write the content of the new error HttpResponseMessage writeErrorResponseTask = errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream); } catch (Exception ex) { // Failed creating the error response task. Likely cause is a formatter exception // before the write task could be created. Create a faulted task to share // the Catch() and Finally() below writeErrorResponseTask = TaskHelpers.FromError(ex); } return(writeErrorResponseTask .Catch((info) => { // Failure writing the error response. Likely cause is a formatter // serialization exception. Create empty error response and // return a non-faulted task. CreateEmptyErrorResponse(httpResponseBase); return info.Handled(); }) .Finally(() => { // Dispose the temporary HttpResponseMessage carrying the error response errorResponse.Dispose(); })); }
protected override void DoAction(HttpResponseBase response, HttpContextBase context) { var jobGroup = context.Request.Params["group"]; _schedulerProvider.Scheduler.ResumeJobs(GroupMatcher <JobKey> .GroupEquals(jobGroup)); }
public MvcForm(HttpResponseBase httpResponse) { throw new InvalidOperationException(MvcResources.MvcForm_ConstructorObsolete); }
/// <summary> /// Writes the entire file to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> protected override void WriteEntireEntity(HttpResponseBase response) { response.OutputStream.Write(FileContents, 0, FileContents.Length); }
public void SignIn(Credential credential, HttpResponseBase httpResponseBase) { this.CustomFormsAuthentication.SignIn(credential.CredentialsId, credential.UserName, credential.FirstName, credential.LastName, credential.IsSystemUser, httpResponseBase); }
/// <summary> /// Writes the file range to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> /// <param name="rangeStartIndex">Range start index</param> /// <param name="rangeEndIndex">Range end index</param> protected override void WriteEntityRange(HttpResponseBase response, long rangeStartIndex, long rangeEndIndex) { response.OutputStream.Write(FileContents, Convert.ToInt32(rangeStartIndex), Convert.ToInt32(rangeEndIndex - rangeStartIndex) + 1); }
private static async Task CreateErrorResponseAsyncCore(HttpResponseMessage errorResponse, HttpResponseBase httpResponseBase) { try { // Asynchronously write the content of the new error HttpResponseMessage await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream); } catch { // Failure writing the error response. Likely cause is a formatter // serialization exception. Create empty error response and // return a non-faulted task. CreateEmptyErrorResponse(httpResponseBase); } finally { // Dispose the temporary HttpResponseMessage carrying the error response errorResponse.Dispose(); } }
public void PublicWriteFile(HttpResponseBase response) { WriteFile(response); }
/// <summary> /// 扫描二维码,用户未关注时,进行关注后的事件推送 /// </summary> /// <param name="httpRequest"></param> /// <param name="msg"></param> public static void ResponseScanUnSubscribeEvent(HttpResponseBase Response, MsgModel msg, ResultCryptography ccg) { var remsg = ""; string str = msg.EventModel.EventKeyModel.EventKey; if (!string.IsNullOrEmpty(str)) { int Id = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(str, @"[^0-9]+", "")); if (Id < 30000 && Id > 0) { msg.MsgType = "news"; ArticelModel articel = new ArticelModel() { Title = "味达美厨师会员招募啦!点击图片即可注册!", Description = "积分好礼、国内外学习考察、新品试用等你来!", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqsSZZuaafJUZfNibZ109B0CXbWpLSaKEdQdibozC0LOibu9Eshs0R1yfgFNOYvI0icb7ntDKXC2k06tVw/0?wx_fmt=jpeg", Url = ConfigurationManager.AppSettings["WeiXinDomain"] + "component/register" }; ArticelModel articel2 = new ArticelModel() { Title = "会员扫码须知", Description = "会员扫码须知", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqtaGUZZoklAKp1sE9eqTK2Mia7RSpH0AyT3lP5BaxNJkiagobOIz3Gpe2ZQs3HYz8icFKw3wxic35KApQ/0?wx_fmt=jpeg", Url = "http://jifenweixin.shinho.net.cn/#/component/activityrule" }; ArticelModel articel3 = new ArticelModel() { Title = "即日起至2月10日,凡任务达标者即可瓜分20万积分红包!", Description = "即日起至2月10日,凡任务达标者即可瓜分20万积分红包!", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqtIndjMF7wbHqDy3CVVvrmTHXAdA9QtewoUvqgazfLlCmfhjExN3HuHk7sbtgp6trxNqt64Z01uqA/0?wx_fmt=jpeg", Url = "http://mp.weixin.qq.com/s/5H6_rnk86ai2fOs-ChI2Gg" }; msg.Articles = new List <ArticelModel>(); msg.Articles.Add(articel); msg.Articles.Add(articel2); msg.Articles.Add(articel3); remsg = XmlHelpler.GetArticlesXml(msg); } else { msg.MsgType = "news"; ArticelModel articel = new ArticelModel() { Title = "味达美厨师会员招募啦!点击图片即可注册!", Description = "积分好礼、国内外学习考察、新品试用等你来!", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqsSZZuaafJUZfNibZ109B0CXbWpLSaKEdQdibozC0LOibu9Eshs0R1yfgFNOYvI0icb7ntDKXC2k06tVw/0?wx_fmt=jpeg", Url = ConfigurationManager.AppSettings["WeiXinDomain"] + "component/register" }; ArticelModel articel2 = new ArticelModel() { Title = "会员扫码须知", Description = "会员扫码须知", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqtaGUZZoklAKp1sE9eqTK2Mia7RSpH0AyT3lP5BaxNJkiagobOIz3Gpe2ZQs3HYz8icFKw3wxic35KApQ/0?wx_fmt=jpeg", Url = "http://jifenweixin.shinho.net.cn/#/component/activityrule" }; ArticelModel articel3 = new ArticelModel() { Title = "即日起至2月10日,凡任务达标者即可瓜分20万积分红包!", Description = "即日起至2月10日,凡任务达标者即可瓜分20万积分红包!", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqtIndjMF7wbHqDy3CVVvrmTHXAdA9QtewoUvqgazfLlCmfhjExN3HuHk7sbtgp6trxNqt64Z01uqA/0?wx_fmt=jpeg", Url = "http://mp.weixin.qq.com/s/5H6_rnk86ai2fOs-ChI2Gg" }; msg.Articles = new List <ArticelModel>(); msg.Articles.Add(articel); msg.Articles.Add(articel2); msg.Articles.Add(articel3); remsg = XmlHelpler.GetArticlesXml(msg); } } else { msg.MsgType = "news"; ArticelModel articel = new ArticelModel() { Title = "味达美厨师会员招募啦!点击图片即可注册!", Description = "积分好礼、国内外学习考察、新品试用等你来!", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqsSZZuaafJUZfNibZ109B0CXbWpLSaKEdQdibozC0LOibu9Eshs0R1yfgFNOYvI0icb7ntDKXC2k06tVw/0?wx_fmt=jpeg", Url = ConfigurationManager.AppSettings["WeiXinDomain"] + "component/register" }; ArticelModel articel2 = new ArticelModel() { Title = "会员扫码须知", Description = "会员扫码须知", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqtaGUZZoklAKp1sE9eqTK2Mia7RSpH0AyT3lP5BaxNJkiagobOIz3Gpe2ZQs3HYz8icFKw3wxic35KApQ/0?wx_fmt=jpeg", Url = "http://jifenweixin.shinho.net.cn/#/component/activityrule" }; ArticelModel articel3 = new ArticelModel() { Title = "即日起至2月10日,凡任务达标者即可瓜分20万积分红包!", Description = "即日起至2月10日,凡任务达标者即可瓜分20万积分红包!", PicUrl = "https://mmbiz.qpic.cn/mmbiz_jpg/uuwJXDpEBqtIndjMF7wbHqDy3CVVvrmTHXAdA9QtewoUvqgazfLlCmfhjExN3HuHk7sbtgp6trxNqt64Z01uqA/0?wx_fmt=jpeg", Url = "http://mp.weixin.qq.com/s/5H6_rnk86ai2fOs-ChI2Gg" }; msg.Articles = new List <ArticelModel>(); msg.Articles.Add(articel); msg.Articles.Add(articel2); msg.Articles.Add(articel3); remsg = XmlHelpler.GetArticlesXml(msg); } Response.Write(GetMsg(remsg, ccg)); }
internal static async Task<bool> PrepareHeadersAsync(HttpResponseBase responseBase, HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger, CancellationToken cancellationToken) { Contract.Assert(response != null); HttpResponseHeaders responseHeaders = response.Headers; Contract.Assert(responseHeaders != null); HttpContent content = response.Content; bool isTransferEncodingChunked = responseHeaders.TransferEncodingChunked == true; HttpHeaderValueCollection<TransferCodingHeaderValue> transferEncoding = responseHeaders.TransferEncoding; if (content != null) { HttpContentHeaders contentHeaders = content.Headers; Contract.Assert(contentHeaders != null); if (isTransferEncodingChunked) { // According to section 4.4 of the HTTP 1.1 spec, HTTP responses that use chunked transfer // encoding must not have a content length set. Chunked should take precedence over content // length in this case because chunked is always set explicitly by users while the Content-Length // header can be added implicitly by System.Net.Http. contentHeaders.ContentLength = null; } else { Exception exception = null; // Copy the response content headers only after ensuring they are complete. // We ask for Content-Length first because HttpContent lazily computes this // and only afterwards writes the value into the content headers. try { var unused = contentHeaders.ContentLength; } catch (Exception ex) { exception = ex; } if (exception != null) { ExceptionContext exceptionContext = new ExceptionContext(exception, WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength, request, response); await exceptionLogger.LogAsync(exceptionContext, cancellationToken); SetEmptyErrorResponse(responseBase); return false; } } // Select output buffering based on the user-controlled buffering policy bool isBuffered = _bufferPolicySelector.Value != null ? _bufferPolicySelector.Value.UseBufferedOutputStream(response) : true; responseBase.BufferOutput = isBuffered; } // Ignore the Transfer-Encoding header if it is just "chunked"; the host will provide it when no // Content-Length is present and BufferOutput is disabled (and this method guarantees those conditions). // HttpClient sets this header when it receives chunked content, but HttpContent does not include the // frames. The ASP.NET contract is to set this header only when writing chunked frames to the stream. // A Web API caller who desires custom framing would need to do a different Transfer-Encoding (such as // "identity, chunked"). if (isTransferEncodingChunked && transferEncoding.Count == 1) { transferEncoding.Clear(); // In the case of a conflict between a Transfer-Encoding: chunked header and the output buffering // policy, honor the Transnfer-Encoding: chunked header and ignore the buffer policy. // If output buffering is not disabled, ASP.NET will not write the TransferEncoding: chunked header. responseBase.BufferOutput = false; } return true; }
private static void SetStatusCode(HttpResponseBase response, int code) { response.Clear(); response.TrySkipIisCustomErrors = true; response.StatusCode = code; }
private static void SetEmptyErrorResponse(HttpResponseBase httpResponseBase) { ClearContentAndHeaders(httpResponseBase); httpResponseBase.StatusCode = (int)HttpStatusCode.InternalServerError; httpResponseBase.SuppressContent = true; }
/// <summary> /// ProcessLogin is responsibile for taking information from a request and ensureing that there is a maplarge user available /// with the correct permissions.For OAuth it expects a Bearer token that is then used to gernerate user + permissions. ///In the maplarge API pipeline ProcessLogin only gets called by Auth/Login api. /// </summary> /// <param name="request">an http request that contains an Authorization Bearer token</param> /// <param name="response">not used by this plugin</param> /// <param name="expiration">lifetime for any maplarge generated token </param> /// <returns>returns authorization info with user and a MapLarge token that can be used for api calls.</returns> public override AuthResult ProcessLogin(HttpRequestBase request, HttpResponseBase response, int expiration) { if (!_isInitialized) { throw new Exception("The OAuth auth plugin is not initialized!"); } // collect the actual header values var actualHeaderValues = new Dictionary <string, string[]>(); //get the Authorization header string key = "Authorization"; string headerVal = request.Headers[key]; if (string.IsNullOrWhiteSpace(headerVal)) { return(FailedAuth($"{key} header is not present", request)); } //get the access token. var headerPieces = headerVal.Split(' '); if (headerPieces.Length != 2) { return(FailedAuth($"{key} header does not contain type and token.", request)); } if (string.Compare(headerPieces[0], "Bearer", true) != 0) { return(FailedAuth($"Token type is not a Bearer token. Actual:{headerPieces[0]}", request)); } var accesstoken = headerPieces[1]; //validate the token List <Claim> userContext = null; try { if (_config.externalValidationOptions != null && !string.IsNullOrWhiteSpace(_config.externalValidationOptions.validationUri)) { userContext = ValidateTokenExternal(accesstoken).GetAwaiter().GetResult().ToList(); } else { userContext = ValidateTokenInternal(accesstoken).GetAwaiter().GetResult().ToList(); } } catch (Exception ex) { return(FailedAuth($"The provided access_token cannot be validated. Either the token is invalid, the token validation options have been misconfigured or the token validation services are unavailable. ex:{ ex.Message}", request)); } //look at the claims get user claim based off the identity key specified in config string userName = userContext.FirstOrDefault(c => _config.identity.Contains(c.Type))?.Value; if (string.IsNullOrWhiteSpace(userName)) { return(FailedAuth($"The provided username is empty. Either the token is invalid, the token identity option is misconfigured.", request)); } string lowerUserName = userName.ToLower().Trim(); //also normalize the username. remove any spaces replace wiuth underscores lowerUserName = lowerUserName.Replace(" ", "_"); //here the claims would be retrieved from the token //those claims would then be mapped to maplarge groups. //if role claim not set all claims are used var claimLookup = ClaimsToLookupKeys(userContext); try { //once the claims are retrived from the token and made available //query the group provider to see which groups if any this user has access to. claimLookup[GROUP_MEMBERSHIP_KEY] = GetGroupsFromProvider(accesstoken); } catch (Exception ex) { return(FailedAuth($"Cannot retrieve entitlements for the given token. Either the token is invalid, the token entitlement endpoints options have been misconfigured or the entitlement services are unavailable. ex:{ ex.Message}", request)); } //are there any claims that are configured for access? if not reject user. try { CheckSystemAccess(claimLookup); } catch (Exception ex) { return(FailedAuth(ex.Message, request)); } //define the username in the MapLarge format if its not already an email. var mlUsername = lowerUserName.Contains("@") ? lowerUserName : $"{lowerUserName}@{_config.userNameEmailDomain}"; //builds an AuthResult given the user and claim to group mapping defined in GroupRequirements definition return(BuildAuthResultFromUserAndGroups(mlUsername, claimLookup, _config.defaultGroups, request, expiration)); }
public static void SwitchCase(HttpResponseBase Response, MsgModel msgModel, ResultCryptography ccg) { try { switch (msgModel.MsgType.ToLower()) { case "text": ResponseRecevieText(Response, msgModel, ccg); break; case "image": if (msgModel.ImageModel != null) { ResponseReceviePic(Response, msgModel, ccg); } break; case "voice": if (msgModel.VoiceModel != null) { ResponseRecevieAudio(Response, msgModel, ccg); } break; case "video": if (msgModel.VideoModel != null) { ResponseRecevieVideo(Response, msgModel, ccg); } break; case "location": if (msgModel.LocationModel != null) { ResponseLocaltonEvent(Response, msgModel, ccg); } break; case "link": if (msgModel.LinkModel != null) { ResponseRecevieLink(Response, msgModel, ccg); } break; case "event": //LogHelper.WriteLog(msgModel.EventModel.Event.ToLower()); switch (msgModel.EventModel.Event.ToLower()) { case "subscribe": //用户未关注时,进行关注后的事件推送 if (msgModel.EventModel.EventKeyModel != null) { ResponseSubscribeEvent(Response, msgModel, ccg); } else //关注 { ResponseNoEvent(Response, msgModel, ccg); } break; case "unsubscribe": //取消关注 ResponseUnSubscribeEvent(Response, msgModel, ccg); break; case "scan": //用户已关注时的事件推送 if (msgModel.EventModel.EventKeyModel != null) { ResponseScanSubscribeEvent(Response, msgModel, ccg); } ; break; case "location": //上报地理位置事件 if (msgModel.EventModel.LocationEventModel != null) { //ResponseLocaltonEvent(Response, msgModel, ccg); } ; break; case "click": //自定义菜单事件 if (msgModel.EventModel.ClickEventModel != null) { ResponseClickEvent(Response, msgModel, ccg); } ; break; case "scancode_waitmsg": //扫码带提示 if (msgModel.EventModel.ClickEventModel != null) { ResponseAdvClickEvent(Response, msgModel, ccg); } ; break; case "scancode_push": //扫码推事件 if (msgModel.EventModel.ClickEventModel != null) { ResponseAdvClickEvent(Response, msgModel, ccg); } ; break; case "pic_sysphoto": //系统拍照发图 if (msgModel.EventModel.ClickEventModel != null) { } ; break; case "pic_photo_or_album": //拍照或者相册发图 if (msgModel.EventModel.ClickEventModel != null) { } ; break; case "pic_weixin": //微信相册发图 if (msgModel.EventModel.ClickEventModel != null) { } ; break; case "location_select": //发送位置 if (msgModel.EventModel.ClickEventModel != null) { } ; break; default: break; } break; default: break; } } catch (Exception ex) { LogHelper.WriteLog(string.Format("接收消息-{0}\n{1}\n{2}", ex.Message, ex.Source, ex.StackTrace)); } }
/// <summary> /// Constructs a instance of markup minification response filter /// </summary> /// <param name="response">HTTP response</param> /// <param name="configuration">WebMarkupMin configuration</param> /// <param name="minificationManager">Markup minification manager</param> public MarkupMinificationFilterStream(HttpResponseBase response, WebMarkupMinConfiguration configuration, IMarkupMinificationManager minificationManager) : this(response, configuration, minificationManager, string.Empty, Encoding.Default) { }
private static HttpContextBase CreateStubContextBase(HttpResponseBase response) { Mock<HttpContextBase> mock = new Mock<HttpContextBase>(); mock.SetupGet(m => m.Response).Returns(response); IDictionary items = new Dictionary<object, object>(); mock.SetupGet(m => m.Items).Returns(items); return mock.Object; }
/// <summary> /// 取消关注事件 /// </summary> /// <param name="httpRequest"></param> /// <param name="msg"></param> public static void ResponseUnSubscribeEvent(HttpResponseBase Response, MsgModel msg, ResultCryptography ccg) { var remsg = XmlHelpler.GetUnSubscribeXml(msg); Response.Write(GetMsg(remsg, ccg)); }