public void Members ()
		{
			WebBodyFormatMessageProperty p = new WebBodyFormatMessageProperty (WebContentFormat.Json);
			Assert.AreEqual ("WebBodyFormatMessageProperty", WebBodyFormatMessageProperty.Name, "#1");
			Assert.AreEqual (WebContentFormat.Json, p.Format, "#2");
			Assert.AreEqual ("WebBodyFormatMessageProperty: WebContentFormat=Json", p.ToString (), "#3");
		}
 /// <summary>
 /// Apply Json settings to the message 
 /// </summary>
 /// <param name="fault"></param>
 protected virtual void ApplyJsonSettings(ref Message fault)
 {
     // Use JSON encoding
     var jsonFormatting =
       new WebBodyFormatMessageProperty(WebContentFormat.Json);
     fault.Properties.Add(WebBodyFormatMessageProperty.Name, jsonFormatting);
 }
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
//            var newEx = new FaultException(string.Format("WCF接口出错 {0}", error.TargetSite.Name));
//            var newEx = new FaultException(error.Message);
//            MessageFault msgFault = newEx.CreateMessageFault();
//            fault = Message.CreateMessage(version, msgFault, newEx.Action);

            string errMsg = new JavaScriptSerializer().Serialize(new Fault(error.Message, "测试"));

            fault = Message.CreateMessage(version, "",errMsg, new DataContractJsonSerializer(typeof (string)));

            // tell WCF to use JSON encoding rather than default XML  
            WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            // Add the formatter to the fault  
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            //Modify response  
            HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();

            // return custom error code, 500.  
            rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
            rmp.StatusDescription = "InternalServerError";

            //Mark the jsonerror and json content  
            rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
            rmp.Headers[HttpResponseHeader.ContentEncoding] = "utf-8";
            rmp.Headers["jsonerror"] = "true";

            //Add to msg  
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp); 
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            var errType = error.GetType();
            var rmp = new HttpResponseMessageProperty();
            var fe = error as FaultException<int>;
            if (fe != null)
            {
                //Detail for the returned value
                var faultCode = fe.Detail;
                var cause = fe.Message;

                //The json serializable object
                var msErrObject = new Result { errorType = errType.Name, install_status = faultCode, message = cause};

                //The fault to be returned
                fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType()));

                //fault = Message.CreateMessage(version, new FaultCode(errType.Name), error.Message, "");
                var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

                // Add the formatter to the fault
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
                // return custom error code, 400.
                rmp.StatusCode = HttpStatusCode.BadRequest;
                rmp.StatusDescription = "Bad request";
            }
            else
            {
                //Arbitraty error
                var msErrObject = new Result { errorType = errType.Name, install_status = 0, message = error.Message };
                // create a fault message containing our FaultContract object
                fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType()));
                // tell WCF to use JSON encoding rather than default XML
                var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
                //Internal server error with exception mesasage as status.
                bool isForbidden = false;
                var webEx = error as WebException;
                if (webEx != null)
                {
                    var httpResp = (HttpWebResponse) webEx.Response;
                    if (httpResp != null)
                        isForbidden = httpResp.StatusCode == HttpStatusCode.Forbidden;
                }
                if ((error is AuthenticationException) || isForbidden)
                    rmp.StatusCode = HttpStatusCode.Forbidden;
                else
                    rmp.StatusCode = HttpStatusCode.InternalServerError;
                rmp.StatusDescription = error.Message;
            }
            //Mark the jsonerror and json content
            rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
            rmp.Headers["jsonerror"] = "true";

            //Add to fault
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
 public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
 {
     Message message = Message.CreateMessage(messageVersion, null, new MyJSSBodyWriter(result));
     HttpResponseMessageProperty httpProp = new HttpResponseMessageProperty();
     message.Properties.Add(HttpResponseMessageProperty.Name, httpProp);
     httpProp.Headers[HttpResponseHeader.ContentType] = "application/json";
     WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(WebContentFormat.Raw);
     message.Properties.Add(WebBodyFormatMessageProperty.Name, bodyFormat);
     return message;
 }
        /// <summary>
        /// Enables the creation of a custom <see cref="FaultException" /> that is returned from an exception in the course of a service method.
        /// </summary>
        /// <param name="error">The <see cref="Exception" /> object thrown in the course of the service operation.</param>
        /// <param name="version">The SOAP version of the message.</param>
        /// <param name="fault">The <see cref="Message" /> object that is returned to the client, or service, in the duplex case.</param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            fault = Message.CreateMessage(version, "", new JsonFault(error), new DataContractJsonSerializer(typeof(JsonFault)));

            WebBodyFormatMessageProperty jsonFormatting = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, jsonFormatting);

            HttpResponseMessageProperty httpResponse = new HttpResponseMessageProperty
            {
                StatusCode = HttpStatusCode.InternalServerError,
                StatusDescription = error.Message,
            };

            fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
        }
Beispiel #7
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            fault = Message.CreateMessage(version, "", new JsonError(error), new DataContractJsonSerializer(typeof(JsonError)));

            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            var rmp = new HttpResponseMessageProperty()
            {
                StatusCode = HttpStatusCode.InternalServerError,
                StatusDescription = "Uknown exception…"
            };
            rmp.Headers[HttpResponseHeader.ContentType] = "application/json";

            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     /*
      * See
      * http://www.zamd.net/2008/07/08/ErrorHandlingWithWebHttpBindingForAjaxJSON.aspx
      * http://decav.com/blogs/andre/archive/2007/11/03/wcf-throwing-exceptions-with-webhttpbinding.aspx
      * http://blog.wadolabs.com/2009/03/wcf-exception-handling-with-ierrorhandler/
      */
     fault = Message.CreateMessage(version, "", new ExceptionInfo(error), new DataContractJsonSerializer(typeof(ExceptionInfo)));
     var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
     fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
     var rmp = new HttpResponseMessageProperty{
         StatusCode = HttpStatusCode.InternalServerError,
         StatusDescription = error.Message,
     };
     rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
     fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
 }
Beispiel #9
0
            WebContentFormat ExtractFormatFromMessage(Message message)
            {
                object messageFormatProperty;

                message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out messageFormatProperty);
                if (messageFormatProperty == null)
                {
                    return(WebContentFormat.Xml);
                }

                WebBodyFormatMessageProperty typedMessageFormatProperty = messageFormatProperty as WebBodyFormatMessageProperty;

                if ((typedMessageFormatProperty == null) ||
                    (typedMessageFormatProperty.Format == WebContentFormat.Default))
                {
                    return(WebContentFormat.Xml);
                }

                return(typedMessageFormatProperty.Format);
            }
Beispiel #10
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            var logger = LogManager.GetCurrentClassLogger();
            logger.Error(error, error.Message);

            // Create message
            var jsonError = new JsonErrorDetails { Message = error.Message, ExceptionType = error.ToLogExceptionEx("") };
            fault = Message.CreateMessage(version, "", jsonError, new DataContractJsonSerializer(typeof(JsonErrorDetails)));

            // Tell WCF to use JSON encoding rather than default XML
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            // Modify response
            var rmp = new HttpResponseMessageProperty
            {
                StatusCode = HttpStatusCode.BadRequest,
                StatusDescription = "Bad Request"
            };
            rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
        }
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     if (error is NodeLoadException)
     {
         fault = Message.CreateMessage(version, "",error.Message, new DataContractJsonSerializer(typeof(string)));
         var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
         fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
         var rmp = new HttpResponseMessageProperty();
         rmp.StatusCode = System.Net.HttpStatusCode.BadRequest;
         rmp.StatusDescription = "See fault object for more information.";
         fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
     }
     else
     {
         fault = Message.CreateMessage(version, "", error.Message, 
             new DataContractJsonSerializer(typeof(string)));
         var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
         fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
         var rmp = new HttpResponseMessageProperty();
         rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
         rmp.StatusDescription = "Uknown exception...";
         fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
     }
 }
Beispiel #12
0
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     WebProtocolException webError = error as WebProtocolException;
     string errorMessage = (this.IncludeExceptionDetailInFaults) ? error.Message : "The server encountered an error processing the request. Please see the server logs for more details.";
     if (webError == null)
     {
         if (error is SecurityAccessDeniedException) webError = new WebProtocolException(HttpStatusCode.Unauthorized, errorMessage, error);
         else if (error is ServerTooBusyException) webError = new WebProtocolException(HttpStatusCode.ServiceUnavailable, errorMessage, error);
         else if (error is FaultException)
         {
             FaultException fe = error as FaultException;
             if (fe.Code.IsSenderFault)
             {
                 if (fe.Code.SubCode.Name == "FailedAuthentication")
                 {
                     webError = new WebProtocolException(HttpStatusCode.Unauthorized, fe.Reason.Translations[0].Text, fe);
                 }
                 else
                 {
                     webError = new WebProtocolException(HttpStatusCode.BadRequest, fe.Reason.Translations[0].Text, fe);
                 }
             }
             else
             {
                 webError = new WebProtocolException(HttpStatusCode.InternalServerError, fe.Reason.Translations[0].Text, fe);
             }
         }
         else
         {
             webError = new WebProtocolException(HttpStatusCode.InternalServerError, errorMessage, error);
         }
     }
     if (version == MessageVersion.None)
     {
         WebMessageFormat format = WebMessageFormat.Xml;
         object dummy;
         if (OperationContext.Current.IncomingMessageProperties.TryGetValue(ResponseWebFormatPropertyAttacher.PropertyName, out dummy))
         {
             format = (WebMessageFormat) dummy;
         }
         fault = Message.CreateMessage(MessageVersion.None, null, new ErrorBodyWriter() { Error = webError, Format = format });
         HttpResponseMessageProperty prop = new HttpResponseMessageProperty();
         prop.StatusCode = webError.StatusCode;
         prop.StatusDescription = webError.StatusDescription;
         if (format == WebMessageFormat.Json)
         {
             prop.Headers[HttpResponseHeader.ContentType] = "application/json";
         }
         else if (webError.IsDetailXhtml)
         {
             prop.Headers[HttpResponseHeader.ContentType] = "text/html";
         }
         fault.Properties[HttpResponseMessageProperty.Name] = prop;
         WebBodyFormatMessageProperty formatProp = new WebBodyFormatMessageProperty((format == WebMessageFormat.Json) ? WebContentFormat.Json : WebContentFormat.Xml);
         fault.Properties[WebBodyFormatMessageProperty.Name] = formatProp;
     }
     if (this.EnableAspNetCustomErrors && HttpContext.Current != null)
     {
         HttpContext.Current.AddError(error);
     }
 }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            HttpStatusCode statusCode;
            if (error is SecurityAccessDeniedException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            else if (error is BizException)
            {
                statusCode = HttpStatusCode.ServiceUnavailable;
            }
            else
            {
                statusCode = HttpStatusCode.InternalServerError;
            }
            H.Core.Utility.ResultEntity<object> eb = new ResultEntity<object>();

            H.Core.Utility.RestServiceError errorData = new RestServiceError()
            {
                StatusCode = (int)statusCode,
                StatusDescription = HttpWorkerRequest.GetStatusDescription((int)statusCode),
                Faults = new List<Error>()
            };

            var errorEntity = new Error();
            errorEntity.ErrorCode = "00000";
            errorEntity.ErrorDescription = error.ToString();
            errorEntity.ErrorMessage = error.Message;
            errorData.Faults.Add(errorEntity);
            eb.ServiceError = errorData;

            if (version == MessageVersion.None && WebOperationContext.Current != null)
            {
                WebMessageFormat messageFormat = WebOperationContext.Current.OutgoingResponse.Format ?? WebMessageFormat.Xml;
                WebContentFormat contentFormat = WebContentFormat.Xml;
                string contentType = "application/xml";

                if (messageFormat == WebMessageFormat.Json)
                {
                    contentFormat = WebContentFormat.Json;
                    contentType = "application/json";
                }

                WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(contentFormat);

                HttpResponseMessageProperty responseMessage = new HttpResponseMessageProperty();
                responseMessage.StatusCode = statusCode;
                responseMessage.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)responseMessage.StatusCode);
                responseMessage.Headers[HttpResponseHeader.ContentType] = contentType;
                responseMessage.Headers["X-HTTP-StatusCode-Override"] = "500";

                fault = Message.CreateMessage(MessageVersion.None, null, new RestServiceErrorWriter() { Error = eb, Format = contentFormat });
                fault.Properties[WebBodyFormatMessageProperty.Name] = bodyFormat;
                fault.Properties[HttpResponseMessageProperty.Name] = responseMessage;
            }

            //记录日志
            if (!(error is BizException))
            {
                ExceptionHelper.HandleException(error);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Masks the exceptions occurred on the service returning a well defined error object
        /// </summary>
        /// <remarks>This method is invoked right after the error occurs and can be used to mask the error 
        /// in a customized way</remarks>
        /// <param name="error">Exception</param>
        /// <param name="version">Version</param>
        /// <param name="fault">Message</param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            Error errObject = null;
            var rmp = new HttpResponseMessageProperty();
            var statusCode = HttpStatusCode.InternalServerError;
            
            if (error is BusinessException)
            {
                //casts the business exception
                var businessException = (BusinessException) error;
                //creates the error object to be returned to the client
                errObject = new Error(businessException.ErrorContextInfo.ErrorId, businessException.ErrorContextInfo.ErrorCode, businessException.ErrorContextInfo.ErrorDescription, (int)HttpStatusCode.BadRequest, businessException.ErrorContextInfo.AdditionalInformation);
                // return custom error code.
                statusCode = HttpStatusCode.BadRequest;
                // put appropriate description 
                rmp.StatusDescription = "See fault object for more information.";
            }
            else if (error is FaultException && OperationContext.Current != null)
            {
                var token = new OperationContextManager().GetValueFromHeader(TOKEN);

                if (string.IsNullOrEmpty(token))
                {
                    var errorContextInformation = ErrorFactory.CreateAndLogError(Errors.SRVEX20000, ErrorHandlerHelper.GetServiceMethod(error), exception: error);
                    errObject = new Error(errorContextInformation.ErrorId, errorContextInformation.ErrorCode, errorContextInformation.ErrorDescription, (int)HttpStatusCode.Unauthorized, errorContextInformation.AdditionalInformation);
                    statusCode = HttpStatusCode.Unauthorized;                    
                }
                else
                {
                    var errorContextInformation = ErrorFactory.CreateAndLogError(Errors.SRVEX20004, ErrorHandlerHelper.GetServiceMethod(error), exception: error);
                    errObject = new Error(errorContextInformation.ErrorId, errorContextInformation.ErrorCode, errorContextInformation.ErrorDescription, (int)HttpStatusCode.PreconditionFailed, errorContextInformation.AdditionalInformation);
                    statusCode = HttpStatusCode.PreconditionFailed;                    
                }

                // put appropriate description 
                rmp.StatusDescription = "See fault object for more information.";
            }
            else if (error is AccessDeniedException)
            {
                var accessDeniedException = error as AccessDeniedException;

                switch (accessDeniedException.Code)
                {
                    case "SRVEX20000":
                        errObject = new Error(accessDeniedException.ErrorContextInfo.ErrorId, accessDeniedException.ErrorContextInfo.ErrorCode, ResourceErrors.SRVEX20000, (int)HttpStatusCode.Unauthorized, accessDeniedException.ErrorContextInfo.AdditionalInformation);
                        statusCode = HttpStatusCode.Unauthorized;
                        break;
                    case "SRVEX20001":
                        errObject = new Error(accessDeniedException.ErrorContextInfo.ErrorId, accessDeniedException.ErrorContextInfo.ErrorCode, ResourceErrors.SRVEX20001, (int)HttpStatusCode.Forbidden, accessDeniedException.ErrorContextInfo.AdditionalInformation);
                        statusCode = HttpStatusCode.Forbidden;
                        break;
                    case "SRVEX20005":
                        errObject = new Error(accessDeniedException.ErrorContextInfo.ErrorId, accessDeniedException.ErrorContextInfo.ErrorCode, ResourceErrors.SRVEX20005, (int)HttpStatusCode.Forbidden, accessDeniedException.ErrorContextInfo.AdditionalInformation, string.Format(PORTAL_URL, accessDeniedException.ErrorContextInfo.ShortName));
                        statusCode = HttpStatusCode.Forbidden;
                        break;
                    case "SRVEX20006":
                        errObject = new Error(accessDeniedException.ErrorContextInfo.ErrorId, accessDeniedException.ErrorContextInfo.ErrorCode, ResourceErrors.SRVEX20006, (int)HttpStatusCode.Forbidden, accessDeniedException.ErrorContextInfo.AdditionalInformation);
                        statusCode = HttpStatusCode.Forbidden;
                        break;          
                    case "SRVEX20007":
                        errObject = new Error(accessDeniedException.ErrorContextInfo.ErrorId, accessDeniedException.ErrorContextInfo.ErrorCode, ResourceErrors.SRVEX20007, (int)HttpStatusCode.Forbidden, accessDeniedException.ErrorContextInfo.AdditionalInformation);
                        statusCode = HttpStatusCode.Forbidden;
                        break;
                    case "SRVEX30000":
                        errObject = new Error(accessDeniedException.ErrorContextInfo.ErrorId, accessDeniedException.ErrorContextInfo.ErrorCode, ResourceErrors.SRVEX30000, (int)HttpStatusCode.Forbidden, accessDeniedException.ErrorContextInfo.ErrorDescription);
                        statusCode = HttpStatusCode.Forbidden;
                        break;
                }                
                // put appropriate description 
                rmp.StatusDescription = "See fault object for more information.";
            }
            else if (error is ValidationException)
            {
                var validationException = error as ValidationException;

                // no translations required
                statusCode = HttpStatusCode.BadRequest;
                errObject = new Error(validationException.ErrorContextInfo.ErrorId, validationException.ErrorContextInfo.ErrorCode, validationException.ErrorContextInfo.ErrorDescription, (int)statusCode, validationException.ErrorContextInfo.AdditionalInformation);                 

                // put appropriate description 
                rmp.StatusDescription = "See fault object for more information.";                
            }
            else
            {
                //build the context information
                var errorContextInformation = ErrorFactory.CreateAndLogError(Errors.SRVEX00001, ErrorHandlerHelper.GetServiceMethod(error), exception: error);
                //creates the error object to be returned to the client
                errObject = new Error(errorContextInformation.ErrorId, errorContextInformation.ErrorCode, errorContextInformation.ErrorDescription, (int)HttpStatusCode.InternalServerError, errorContextInformation.AdditionalInformation);
                statusCode = HttpStatusCode.InternalServerError;
                // put appropriate description 
                rmp.StatusDescription = "Unknown exception.";
            }
            // create a fault message containing our FaultContract object
            fault = Message.CreateMessage(version, "", errObject, new DataContractJsonSerializer(typeof(Error)));

            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
            WebOperationContext.Current.OutgoingResponse.ContentType = JSON_CONTENT_TYPE;
            WebOperationContext.Current.OutgoingResponse.StatusCode = statusCode;
            rmp.Headers[JSON_ERROR] = "true";
            
            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);

        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            var operationAction = OperationContext.Current.IncomingMessageHeaders.Action;

            if (operationAction == null)
            {
                var requestBinding = OperationContext.Current.EndpointDispatcher.ChannelDispatcher.BindingName;
                if (requestBinding.Contains("WebHttpBinding"))
                    operationAction = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string;
            }

            DispatchOperation operation = OperationContext.Current
                                               .EndpointDispatcher
                                               .DispatchRuntime
                                               .Operations
                                               .FirstOrDefault(o => o.Action == operationAction);

            if (_useJsonFault)
            {
                var details = error.InnerException != null
                    ? "InnerException available, see server logs for further details"
                    : string.Empty;

                var webHttpError = new WebHttpError { Error = "Unknown Exception", Detail = details };

                var webFaultException = new WebFaultException<WebHttpError>(webHttpError,
                    HttpStatusCode.InternalServerError);

                fault = Message.CreateMessage(version, operationAction, webFaultException);
            }
            else
            {
                var detail = error as FaultException;

                var faultDetail = detail ?? new FaultException(new FaultReason("Unknown Exception"), FaultCode.CreateReceiverFaultCode("Unhandled", ""));

                fault = Message.CreateMessage(version, operationAction, faultDetail, new DataContractJsonSerializer(faultDetail.GetType()));
            }

            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            var rmp = new HttpResponseMessageProperty
            {
                StatusCode = HttpStatusCode.InternalServerError,

                StatusDescription = "See server logs for further details"
            };

            rmp.Headers[HttpResponseHeader.ContentType] = "application/json";

            fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);

            if (WebOperationContext.Current != null)
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
        }
Beispiel #16
0
			public virtual Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
			{
				if (parameters == null)
					throw new ArgumentNullException ("parameters");
				CheckMessageVersion (messageVersion);

				var c = new Dictionary<string,string> ();

				MessageDescription md = GetMessageDescription (MessageDirection.Input);

				if (parameters.Length != md.Body.Parts.Count)
					throw new ArgumentException ("Parameter array length does not match the number of message body parts");

				for (int i = 0; i < parameters.Length; i++) {
					var p = md.Body.Parts [i];
					string name = p.Name.ToUpper (CultureInfo.InvariantCulture);
					if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
					    UriTemplate.QueryValueVariableNames.Contains (name))
						c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
					else
						// FIXME: bind as a message part
						throw new NotImplementedException (String.Format ("parameter {0} is not contained in the URI template {1} {2} {3}", p.Name, UriTemplate, UriTemplate.PathSegmentVariableNames.Count, UriTemplate.QueryValueVariableNames.Count));
				}

				Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);

				Message ret = Message.CreateMessage (messageVersion, (string) null);
				ret.Headers.To = to;

				var hp = new HttpRequestMessageProperty ();
				hp.Method = Info.Method;

#if !NET_2_1
				if (WebOperationContext.Current != null)
					WebOperationContext.Current.OutgoingRequest.Apply (hp);
#endif
				// FIXME: set hp.SuppressEntityBody for some cases.
				ret.Properties.Add (HttpRequestMessageProperty.Name, hp);

				var wp = new WebBodyFormatMessageProperty (ToContentFormat (Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat, null));
				ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);

				return ret;
			}
Beispiel #17
0
			public virtual Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
			{
				if (parameters == null)
					throw new ArgumentNullException ("parameters");
				CheckMessageVersion (messageVersion);

				var c = new Dictionary<string,string> ();

				MessageDescription md = GetMessageDescription (MessageDirection.Input);

				Message ret;
				Uri to;
				object msgpart = null;


				for (int i = 0; i < parameters.Length; i++) {
					var p = md.Body.Parts [i];
					string name = p.Name.ToUpper (CultureInfo.InvariantCulture);
					if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
					    UriTemplate.QueryValueVariableNames.Contains (name))
						c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
					else {
						// FIXME: bind as a message part
						if (msgpart == null)
							msgpart = parameters [i];
						else
							throw new  NotImplementedException (String.Format ("More than one parameters including {0} that are not contained in the URI template {1} was found.", p.Name, UriTemplate));
					}
				}
				ret = Message.CreateMessage (messageVersion, (string) null, msgpart);

				to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
				ret.Headers.To = to;

				var hp = new HttpRequestMessageProperty ();
				hp.Method = Info.Method;

				WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
				var contentFormat = ToContentFormat (msgfmt, msgpart);
				string mediaType = GetMediaTypeString (contentFormat);
				// FIXME: get encoding from somewhere
				hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";

#if !NET_2_1
				if (WebOperationContext.Current != null)
					WebOperationContext.Current.OutgoingRequest.Apply (hp);
#endif
				// FIXME: set hp.SuppressEntityBody for some cases.
				ret.Properties.Add (HttpRequestMessageProperty.Name, hp);

				var wp = new WebBodyFormatMessageProperty (ToContentFormat (Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat, null));
				ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);

				return ret;
			}
Beispiel #18
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (error == null || version == null)
                return;

            fault = Message.CreateMessage(version, "", new ErrorMessage(error), new DataContractJsonSerializer(typeof(ErrorMessage)));
            var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

            var response = WebOperationContext.Current.OutgoingResponse;
            response.ContentType = "application/json";
            response.StatusCode = HttpStatusCode.InternalServerError;
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            HttpStatusCode statusCode;
            if (error is SecurityAccessDeniedException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            else if (error is ServerTooBusyException)
            {
                statusCode = HttpStatusCode.ServiceUnavailable;
            }
            else if (CheckIsBizException(error.GetType()))
            {
                statusCode = HttpStatusCode.OK;
            }
            else
            {
                statusCode = HttpStatusCode.InternalServerError;
            }

            RestServiceError errorData = new RestServiceError()
            {
                StatusCode = (int)statusCode,
                StatusDescription = HttpWorkerRequest.GetStatusDescription((int)statusCode),
                Faults = new List<Error>()
            };

            if (CheckIsBizException(error.GetType()))
            {
                errorData.Faults.Add(new Error()
                {
                    ErrorCode = "11111",
                    ErrorDescription = error.Message
                });
            }
            else
            {
                string show = ConfigurationManager.AppSettings["ShowErrorDetail"];
                bool showDetail = false;
                bool tmp;
                if (!string.IsNullOrWhiteSpace(show) && bool.TryParse(show, out tmp))
                {
                    showDetail = tmp;
                }
                errorData.Faults.Add(new Error()
                {
                    ErrorCode = "00000",
                    ErrorDescription = showDetail ? error.ToString() : "SYSTEM EXCEPTION"
                });
            }

            if (version == MessageVersion.None)
            {
                WebMessageFormat messageFormat = WebOperationContext.Current.OutgoingResponse.Format ?? WebMessageFormat.Xml;
                WebContentFormat contentFormat = WebContentFormat.Xml;
                string contentType = "text/xml";

                if (messageFormat == WebMessageFormat.Json)
                {
                    contentFormat = WebContentFormat.Json;
                    contentType = "application/json";
                }

                WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(contentFormat);

                HttpResponseMessageProperty responseMessage = new HttpResponseMessageProperty();
                responseMessage.StatusCode = HttpStatusCode.OK;
                responseMessage.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)responseMessage.StatusCode);
                responseMessage.Headers[HttpResponseHeader.ContentType] = contentType;
                responseMessage.Headers["X-HTTP-StatusCode-Override"] = "500";

                fault = Message.CreateMessage(MessageVersion.None, null, new RestServiceErrorWriter() { Error = errorData, Format = contentFormat });
                fault.Properties[WebBodyFormatMessageProperty.Name] = bodyFormat;
                fault.Properties[HttpResponseMessageProperty.Name] = responseMessage;
            }
        }
Beispiel #20
0
			Message SerializeReplyCore (MessageVersion messageVersion, object [] parameters, object result)
			{
				// parameters could be null.
				// result could be null. For Raw output, it becomes no output.

				CheckMessageVersion (messageVersion);

				MessageDescription md = GetMessageDescription (MessageDirection.Output);

				// FIXME: use them.
				// var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> ();
				// XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null);
				// var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> ();
				// XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ());

				WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;

				string mediaType = null;
				XmlObjectSerializer serializer = null;

				// FIXME: serialize ref/out parameters as well.

				string name = null, ns = null;

				switch (msgfmt) {
				case WebMessageFormat.Xml:
					serializer = GetSerializer (WebContentFormat.Xml);
					mediaType = "application/xml";
					name = IsResponseBodyWrapped ? md.Body.WrapperName : null;
					ns = IsResponseBodyWrapped ? md.Body.WrapperNamespace : null;
					break;
				case WebMessageFormat.Json:
					serializer = GetSerializer (WebContentFormat.Json);
					mediaType = "application/json";
					name = IsResponseBodyWrapped ? (BodyName ?? md.Body.ReturnValue.Name) : null;
					ns = String.Empty;
					break;
				}

				var contentFormat = ToContentFormat (msgfmt, result);
				Message ret = contentFormat == WebContentFormat.Raw ? new RawMessage ((Stream) result) : Message.CreateMessage (MessageVersion.None, null, new WrappedBodyWriter (result, serializer, name, ns, contentFormat));

				// Message properties

				var hp = new HttpResponseMessageProperty ();
				// FIXME: get encoding from somewhere
				hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";

				// apply user-customized HTTP results via WebOperationContext.
				if (WebOperationContext.Current != null) // this formatter must be available outside ServiceHost.
					WebOperationContext.Current.OutgoingResponse.Apply (hp);

				// FIXME: fill some properties if required.
				ret.Properties.Add (HttpResponseMessageProperty.Name, hp);

				var wp = new WebBodyFormatMessageProperty (contentFormat);
				ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);

				return ret;
			}
        private static Message Serialize(object obj)
        {
            Message message;

            using (var stream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize(stream, obj);
                message = Message.CreateMessage(MessageVersion, Action, new StreamBodyWriter(stream.ToArray()));
            }

            var contentType = "application/octet-stream";
            var httpResponseMessageProperty = new HttpResponseMessageProperty();
            httpResponseMessageProperty.Headers.Add(HttpResponseHeader.ContentType, contentType);
            var webBodyFormatMessageProperty = new WebBodyFormatMessageProperty(WebContentFormat.Raw);

            message.Properties[HttpResponseMessageProperty.Name] = httpResponseMessageProperty;
            message.Properties[WebBodyFormatMessageProperty.Name] = webBodyFormatMessageProperty;

            return message;
        }