private void ThrowWebFault(Exception e, HttpStatusCode statusCode = HttpStatusCode.InternalServerError) { WebFaultData webFaultData = new WebFaultData(e); Exception exception = new WebFaultException <WebFaultData>(webFaultData, statusCode); Log.Error(exception, "Throwing WebFaultException: {@WebFaultData}", webFaultData); throw exception; }
public void ShouldReturnExceptionMessageContainingPrefix() { const string errorMessagePrefix = "message prefix"; WebFaultException <string> webFaultException = _webFaultExceptionCreator.CreateWebFaultException(new Exception(), errorMessagePrefix); StringAssert.Contains(errorMessagePrefix, webFaultException.Detail, "Prefix not contained in message."); }
public void ShouldReturnExceptionMessageContainingOriginalExceptionMessage() { Exception originalException = new Exception("message here"); WebFaultException <string> webFaultException = _webFaultExceptionCreator.CreateWebFaultException(originalException, string.Empty); StringAssert.Contains(originalException.Message, webFaultException.Detail, "Prefix not contained in message."); }
public void ShouldRethrowExceptionInActionWhenItIsAWebFaultExceptionWithString() { var expectedException = new WebFaultException <string>(string.Empty, HttpStatusCode.BadRequest); WebFaultException <string> returnedException = _webFaultExceptionCreator.CreateWebFaultException(expectedException, string.Empty); Assert.AreEqual(expectedException, returnedException, "Expected WebFaultException<string> was not rethrown."); }
public void ShouldThrowWithGivenStatusCodeWhenGivenWebFaultException() { const HttpStatusCode expectedCode = HttpStatusCode.BadGateway; WebFaultException originalException = new WebFaultException(expectedCode); WebFaultException <string> webFaultException = _webFaultExceptionCreator.CreateWebFaultException(originalException, string.Empty); Assert.AreEqual(expectedCode, webFaultException.StatusCode, "Incorrect status code returned."); }
public void ShouldThrowExceptionWithStatusCodeUnauthorizedWhenPackageAuthorizationExceptionThrown() { const HttpStatusCode expectedStatusCode = HttpStatusCode.Unauthorized; var exception = new PackageAuthorizationException(); WebFaultException <string> webFaultException = _webFaultExceptionCreator.CreateWebFaultException(exception, string.Empty); Assert.AreEqual(expectedStatusCode, webFaultException.StatusCode, "Incorrect StatusCode returned."); }
public void ShouldReturnInternalServerErrorWhenGivenOtherException() { const HttpStatusCode expectedStatusCode = HttpStatusCode.InternalServerError; var originalException = new Exception(); WebFaultException <string> webFaultException = _webFaultExceptionCreator.CreateWebFaultException(originalException, string.Empty); Assert.AreEqual(expectedStatusCode, webFaultException.StatusCode, "Incorrect status code returned."); }
public void ShouldThrowExceptionWithStatusCodeNotFoundWhenObjectDoesNotExistExceptionThrown() { const HttpStatusCode expectedStatusCode = HttpStatusCode.NotFound; var exception = new ObjectDoesNotExistException(); WebFaultException <string> webFaultException = _webFaultExceptionCreator.CreateWebFaultException(exception, string.Empty); Assert.AreEqual(expectedStatusCode, webFaultException.StatusCode, "Incorrect StatusCode returned."); }
private void ThrowRejection(HttpStatusCode status, string message) { var rejectEx = new WebFaultException <String>(message, status); rejectEx.Data.Add("HttpStatusCode", rejectEx.StatusCode); //this exception is expected, as it triggers the authentication //to ignore this error while running in VS debugger uncheck the "break when this exception is user handled" box throw rejectEx; }
/// <summary> /// Throws an HTTP exception from a <see cref="T:System.ServiceModel.Web.WebFaultException`1" />. /// </summary> /// <param name="webFaultException">A web service WebFaultException.</param> public static void WebFaultToHttpException(this WebFaultException <string> webFaultException) { if (webFaultException != null) { Throw.HttpResponse( webFaultException.StatusCode, "Web service threw a WebFaultException.", webFaultException.Detail); } }
/// <summary>Creates a fault message from the specified exception.</summary> /// <param name="error">The exception that has been raised.</param> /// <param name="version">The SOAP version of the message.</param> /// <param name="fault">The fault message that is returned to the client.</param> public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { var aex = error as AggregateException; if (aex != null) { if (aex.InnerExceptions.Count > 1) { error = new OwsException(OwsExceptionCode.NoApplicableCode, _Reason, error); } else { error = aex.InnerExceptions[0]; } } var fex = error as FaultException; if (fex == null) { if (error is NotImplementedException) { error = new OwsException(OwsExceptionCode.OperationNotSupported, _Reason, error); } var oex = error as OwsException; if (oex != null) { // [OGC 06-121r9, §8.6] var status = HttpStatusCode.InternalServerError; switch (oex.Code) { case OwsExceptionCode.InvalidParameterValue: case OwsExceptionCode.InvalidUpdateSequence: case OwsExceptionCode.MissingParameterValue: status = HttpStatusCode.BadRequest; break; case OwsExceptionCode.OperationNotSupported: case OwsExceptionCode.OptionNotSupported: status = HttpStatusCode.NotImplemented; break; } fex = new WebFaultException <Ows100.ExceptionReport>((Ows100.ExceptionReport)oex, status); } else { FaultCode fc = FaultCode.CreateReceiverFaultCode("InternalServerError", "http://schemas.microsoft.com/2009/WebFault"); fex = new FaultException(_Reason, fc); } } fault = CreateMessage(fex, version); }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { Type errorType = error.GetType(); bool handled = false; WebFaultException <XElement> webFaultOfXElement = error as WebFaultException <XElement>; if (webFaultOfXElement != null) { handled = true; WebOperationContext.Current.OutgoingResponse.StatusCode = webFaultOfXElement.StatusCode; fault = WebOperationContext.Current.CreateXmlResponse(webFaultOfXElement.Detail); } else if (errorType.IsGenericType && errorType.GetGenericTypeDefinition() == typeof(WebFaultException <>)) { Type genericParameter = errorType.GetGenericArguments()[0]; if (typeof(JsonValue).IsAssignableFrom(genericParameter)) { handled = true; JsonValue detail = (JsonValue)errorType.GetProperty("Detail").GetValue(error, null); HttpStatusCode statusCode = (HttpStatusCode)errorType.GetProperty("StatusCode").GetValue(error, null); WebOperationContext.Current.OutgoingResponse.StatusCode = statusCode; if (detail == null) { WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true; fault = WebOperationContext.Current.CreateStreamResponse(Stream.Null, string.Empty); } else { fault = CreateJsonObjectMessage(version, detail); } } } else if (error is ValidationException) { ValidationException validationError = error as ValidationException; if (validationError != null) { handled = true; JsonObject jsonError = new JsonObject(); foreach (string name in validationError.ValidationResult.MemberNames) { jsonError.Add(name, validationError.ValidationResult.ErrorMessage); } WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; fault = CreateJsonObjectMessage(version, jsonError); } } if (!handled) { this.baseHandler.ProvideFault(error, version, ref fault); } }
public void ShouldThrowWebFaultExceptionWhenUnpublishThrows() { var expectedException = new WebFaultException <string>(null, HttpStatusCode.Accepted); MockedPackageUnpublisher.Setup(pp => pp.UnpublishPackage(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .Throws(new Exception()); MockedWebFaultExceptionFactory.Setup(wfef => wfef.CreateWebFaultException(It.IsAny <Exception>(), It.IsAny <string>())).Returns(expectedException); TestDelegate methodThatShouldThrow = () => PackagePublishingService.Unpublish(null, null, null); ExceptionAssert.Throws(methodThatShouldThrow, expectedException, "Incorrect exception thrown."); }
/// <summary>Creates a fault message from the specified parameters.</summary> /// <param name="fex">The fault exception to create a message from.</param> /// <param name="version">The SOAP version of the message.</param> /// <returns>A fault message.</returns> protected override Message CreateMessage(FaultException fex, MessageVersion version) { var fexd = fex as WebFaultException <Ows100.ExceptionReport>; if (fexd == null) { var oex = new OwsException(OwsExceptionCode.NoApplicableCode, fex); fexd = new WebFaultException <Ows100.ExceptionReport>((Ows100.ExceptionReport)oex, HttpStatusCode.InternalServerError); } return(WebOperationContext.Current.CreateXmlResponse <Ows100.ExceptionReport>(fexd.Detail)); }
/// <summary> /// Rzuć wyjątkiem /// </summary> /// <param name="error">Status błędu</param> /// <param name="code">Kod odpowiedzi HTTP</param> public static void Throw(string error, HttpStatusCode code) { if (WebOperationContext.Current != null) { WebOperationContext.Current.OutgoingResponse.ContentType = "application/json"; } var wfc = new WebFaultException <ErrorDetailWeb> (new ErrorDetailWeb { Error = error }, code); throw wfc; }
public override void Validate(string userName, string password) { if (userName == null || password == null) { throw new ArgumentNullException(); } string str = string.Concat(userName, ":"); string str1 = Settings.Default.BasicAuthUserCredentials.Cast <string>().FirstOrDefault <string>((string t) => t.StartsWith(str)); if (string.IsNullOrWhiteSpace(str1) || !string.Equals(str1.Substring(str.Length), password, StringComparison.InvariantCulture)) { WebFaultException webFaultException = new WebFaultException(HttpStatusCode.Unauthorized); webFaultException.Data.Add("HttpStatusCode", webFaultException.StatusCode); throw webFaultException; } }
// This method validates users. It allows in two users, // test1 and test2 with passwords 1tset and 2tset respectively. // This code is for illustration purposes only and // MUST NOT be used in a production environment because it // is NOT secure. public override void Validate(string userName, string password) { if (null == userName || null == password) { throw new ArgumentNullException(); } if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset")) { // throw new SecurityTokenException("Unknown Username or Password"); // throw new ArgumentException(); //throw new SecurityTokenValidationException("yee haww"); // throw new FaultException("Unknown Username or Incorrect Password"); var rejectEx = new WebFaultException(HttpStatusCode.Unauthorized); rejectEx.Data.Add("HttpStatusCode", rejectEx.StatusCode); throw rejectEx; } }
/// <summary> /// Creates and returns a FaultException if the incoming request is a SOAP request or a WebFaultException if it is a REST request. /// </summary> /// <param name="message">Fault message to show</param> /// <param name="code">Code associated to the error</param> /// <param name="faultDetails">Optional details to add to the error</param> /// <returns>The FaultException or WebFaultException according to the incoming request and the given parameters</returns> public static FaultException CreateFault(string message, int code, FaultExceptionDetail faultDetails = null) { FaultException response = null; //Manage the SOAP or REST different returns if (!(WebOperationContext.Current.IncomingRequest.ContentType.StartsWith("application/json"))) { //SOAP if (faultDetails == null || faultDetails.FieldsErrors.Count == 0) { //The fault doesn't has details response = new FaultException(new FaultReason(message), new FaultCode(code.ToString())); } else { //Fault with details response = new FaultException <FaultExceptionDetail>(faultDetails, new FaultReason(message), new FaultCode(code.ToString())); } } else { //REST if (faultDetails == null || faultDetails.FieldsErrors.Count == 0) { //The fault doesn't has details response = new WebFaultException <ErrorData>(new ErrorData(message, string.Empty), HttpStatusCode.InternalServerError); } else { //Fault with details string details = string.Empty; for (int i = 0; i < faultDetails.FieldsErrors.Count; i++) { details += string.Format("{0}-{1}|", faultDetails.FieldsErrors[i].FieldName, faultDetails.FieldsErrors[i].ErrorMessage); } response = new WebFaultException <ErrorData>(new ErrorData(message, details), HttpStatusCode.InternalServerError); } } return(response); }
public override Exception HandlerException(Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation input, Exception exception) { if (exception is WebFaultException <ExceptionDetail> ) { string note = FormmatException(exception.StackTrace, exception.Message); ExceptionLog.Write(note); throw exception; } if (!(exception is GenericException)) { exception = new GenericException(exception); string notepad = FormmatException(exception.StackTrace, exception.Message); ExceptionLog.Write(notepad); } ExceptionDetail detail = new ExceptionDetail(exception); var result = new WebFaultException <ExceptionDetail>(detail, HttpStatusCode.BadRequest); throw result; }
public override void Validate(string userName, string password) { try { if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { throw new ArgumentNullException(); } var auth = IoC.Instance.Resolve <IAuthenticationProvider>(); auth.Authenticate(userName, password); } catch (Exception ex) { //TODO: разобраться как передать сообщение ошибки var fault = new WebFaultException <Exception>(ex, HttpStatusCode.Unauthorized); // HACK: недокументированный прием передать код статуса fault.Data["HttpStatusCode"] = HttpStatusCode.Unauthorized; throw fault; } }
public override Exception HandlerException(Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation input, Exception exception) { //if (exception is GenericException) // exception = exception; if (exception is WebFaultException <ExceptionDetail> ) { throw exception; } if (!(exception is GenericException)) { exception = new GenericException(exception); } ExceptionDetail detail = new ExceptionDetail(exception); var result = new WebFaultException <ExceptionDetail>(detail, HttpStatusCode.BadRequest); throw result; }
internal WebFaultExceptionWrapper(Exception error) { Fx.Assert(error != null, "error cannot be null"); WebFaultException asWebFaultException = error as WebFaultException; Type errorType = error.GetType(); bool isGenericWebFaultException = errorType.IsGenericType && errorType.GetGenericTypeDefinition() == genericWebFaultExceptionType; if (isGenericWebFaultException || asWebFaultException != null) { this.IsWebFaultException = true; if (isGenericWebFaultException) { this.InitializeFromGenericWebFaultException(error); } else { this.InitializeFromWebFaultException(asWebFaultException); } } }
public object BeforeCall(string operationName, object[] inputs) { try { var user = ConfigurationManager.AppSettings["User"]; var password = ConfigurationManager.AppSettings["Password"]; var auth = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Authorization]; if (auth != null) { if (auth.StartsWith("Basic ")) { var cred = Encoding.UTF8.GetString(Convert.FromBase64String(auth.Substring("Basic ".Length))); var parts = cred.Split(':'); if (user == parts[0] && password == parts[1]) { return(null); } } } } catch (Exception e) { log.Error("Error in validation authentication", e); WebFaultThrower.Throw("An error occurred, please try again later.", HttpStatusCode.ServiceUnavailable); } WebOperationContext.Current.OutgoingResponse.ContentType = "application/json"; var wfc = new WebFaultException <ErrorDetailWeb> (new ErrorDetailWeb { Error = "No authorized bank" }, HttpStatusCode.Unauthorized); throw wfc; }
private void InitializeFromWebFaultException(WebFaultException webFaultException) { this.StatusCode = webFaultException.StatusCode; this.DetailObject = null; this.DetailType = null; }
FaultException TransformException( IMethodInvocation input, Exception exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } Exception outException = null; try { if (!Facility.ExceptionManager.HandleException(exception, ExceptionHandlingPolicyName, out outException)) { return(null); } } catch (Exception x) { Facility.LogWriter.LogError( $@" Facility.ExceptionManager.HandleException throws: {x.DumpString(1)} when processing {exception.DumpString(1)}"); if (ExceptionHandlingPolicyName == ExceptionPolicyProvider.LogAndSwallowPolicyName) { return(null); } if (outException == null) { outException = exception; } } var faultException = outException as FaultException; // try to get the fault, if any var fault = (faultException != null && faultException.GetType().IsGenericType) ? faultException .GetType() .GetProperty(nameof(FaultException <Fault> .Detail)) ?.GetValue(faultException) as Fault : null; // can we return the faultException as we got it if (fault != null && IsFaultSupported(input, fault.GetType())) { return(faultException); } // if the base fault is supported one with all fields copied either to properties or to the Data collection. // Send it with status code 500 to indicate that the fault must be added to the protocol if (IsFaultSupported(input, typeof(Fault))) { fault = Fault.FaultFactory <Exception>(exception); return(new WebFaultException <Fault>(fault, HttpStatusCode.InternalServerError)); } // otherwise construct base WebFaultException with some debug data in the Data property that will be dumped in the logs var exceptionToReturn = new WebFaultException(HttpStatusCode.InternalServerError); if (fault != null) { return(exceptionToReturn .PopulateData( new SortedDictionary <string, string> { ["HandlingInstanceId"] = fault.HandlingInstanceId.ToString(), ["Fault"] = fault.DumpString(), })); } return(exceptionToReturn .PopulateData( new SortedDictionary <string, string> { ["Exception"] = exception.DumpString(), })); }