public Message Get(Message message)
        {
            HttpRequestMessageProperty requestMessageProperty = (HttpRequestMessageProperty) message.Properties[HttpRequestMessageProperty.Name];
            HttpResponseMessageProperty responseMessageProperty = new HttpResponseMessageProperty();

            if ((requestMessageProperty != null) && IsServiceUnchanged(requestMessageProperty.Headers[JsonGlobals.IfModifiedSinceString]))
            {
                Message responseMessage = Message.CreateMessage(MessageVersion.None, string.Empty);
                responseMessageProperty.StatusCode = HttpStatusCode.NotModified;
                responseMessage.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty);
                return responseMessage;
            }

            string proxyContent = this.GetProxyContent(UriTemplate.RewriteUri(this.endpoint.Address.Uri, requestMessageProperty.Headers[HttpRequestHeader.Host]));
            Message response = new WebScriptMetadataMessage(string.Empty, proxyContent);
            responseMessageProperty.Headers.Add(JsonGlobals.LastModifiedString, ServiceLastModifiedRfc1123String);
            responseMessageProperty.Headers.Add(JsonGlobals.ExpiresString, ServiceLastModifiedRfc1123String);
            if (AspNetEnvironment.Current.AspNetCompatibilityEnabled)
            {
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
            }
            else
            {
                responseMessageProperty.Headers.Add(JsonGlobals.CacheControlString, JsonGlobals.publicString);
            }
            response.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty);
            return response;
        }
 public void BeforeSendReply(ref Message reply, object correlationState)
 {
     var state = correlationState as CorsState;
     if (state != null)
     {
         if (state.Message != null)
         {
             reply = state.Message;
         }
         HttpResponseMessageProperty responseProperty = null;
         if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
         {
             responseProperty = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
         }
         if (responseProperty == null)
         {
             responseProperty = new HttpResponseMessageProperty();
             reply.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
         }
         //Acao should be added for all cors responses
         responseProperty.Headers.Set("Access-Control-Allow-Origin", _behavior.AllowOrigin);
         if (state.Message != null)
         {
             //the following headers should only be added for OPTIONS requests
             responseProperty.Headers.Set("Access-Control-Allow-Methods", _behavior.AllowMethods);
             responseProperty.Headers.Set("Access-Control-Allow-Headers", _behavior.AllowHeaders);
         }
     }
 }
예제 #3
0
		internal IncomingWebResponseContext (OperationContext context)
		{
			if (context.IncomingMessageProperties != null)
				hp = (HttpResponseMessageProperty) context.IncomingMessageProperties [HttpResponseMessageProperty.Name];
			else
				hp = new HttpResponseMessageProperty ();
		}
예제 #4
0
        void AuthenticationService_Authenticating(object sender, System.Web.ApplicationServices.AuthenticatingEventArgs e)
        {
            string roles = string.Empty;

            e.Authenticated = new UserValidator().IsUserValid(e.UserName, e.Password, out roles);
            e.AuthenticationIsComplete = true;

            if (e.Authenticated)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    e.UserName,
                    DateTime.Now,
                    DateTime.Now.AddHours(24),
                    true,
                    roles,
                    FormsAuthentication.FormsCookiePath);

                // Encrypt the ticket using machine key
                string encryptedValue = FormsAuthentication.Encrypt(ticket);

                // Attach Cookie to Operation Context header
            HttpResponseMessageProperty response = new HttpResponseMessageProperty();
            response.Headers[HttpResponseHeader.SetCookie] = FormsAuthentication.FormsCookieName + "=" + encryptedValue;
            OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name] = response;
            }
        }
        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 BeginReply_Ignores_HttpResponseMessageProperty_When_Response_Is_Not_HttpMessage()
        {
            Message message = Message.CreateMessage(MessageVersion.None, string.Empty, "some content");
            HttpResponseMessageProperty property = new HttpResponseMessageProperty();
            property.StatusCode = HttpStatusCode.OK;
            property.SuppressEntityBody = false;
            property.Headers.Add(HttpResponseHeader.ContentType, "someType/someSubType");
            message.Properties.Add(HttpResponseMessageProperty.Name, property);

            MockRequestContext innerRequestContext = new MockRequestContext();
            innerRequestContext.OnReplyReceived = innerMessage =>
            {
                HttpResponseMessageProperty innerProperty = innerMessage.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
                Assert.IsNotNull(innerProperty, "The inner HttpMessage instance should have had an HttpResponseMessageProperty.");
                Assert.AreNotSame(property, innerProperty, "The inner HttpResponseMessageProperty should have been a different instance from the one on the response message.");

                Assert.AreEqual(HttpStatusCode.InternalServerError, innerProperty.StatusCode, "HttpResponseMessageProperty.StatusCode should have been HttpStatusCode.InternalServerError.");
                Assert.IsTrue(innerProperty.SuppressEntityBody, "HttpResponseMessageProperty.SuppressEntityBody should have been 'true'.");
                Assert.AreEqual(0, innerProperty.Headers.Count, "HttpResponseMessageProperty.Header.Count should have been zero.");
            };

            HttpMessageEncodingRequestContext requestContext = new HttpMessageEncodingRequestContext(innerRequestContext);
            requestContext.BeginReply(message, null, null);
            Assert.IsTrue(innerRequestContext.BeginReplyCalled, "HttpMessageEncodingRequestContext.BeginReply should have called BeginReply on the inner RequestContext.");
        }
 private HttpResponseMessageProperty CreateResponseProperty()
 {
     var responseProperty = new HttpResponseMessageProperty();
      responseProperty.StatusCode = HttpStatusCode.Unauthorized;
      responseProperty.Headers.Add(BasicAuthenticationHeaderName, string.Format(CultureInfo.InvariantCulture, "Basic realm=\"{0}\"", realm));
      return responseProperty;
 }
 public void BeforeSendReply(ref Message reply, object correlationState)
 {
     if ((reply != null) && reply.IsFault) {
         var property = new HttpResponseMessageProperty { StatusCode = HttpStatusCode.OK };
         reply.Properties[HttpResponseMessageProperty.Name] = property;
     }
 }
        public Message GetFlashPolicy(Message request)
        {
            HttpRequestMessageProperty httpRequestProperty;
            if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                httpRequestProperty = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                if (!httpRequestProperty.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
                {
                    Message reply = Message.CreateMessage(MessageVersion.None, String.Empty);
                    HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty();
                    responseProperty.StatusCode = System.Net.HttpStatusCode.MethodNotAllowed;
                    responseProperty.SuppressEntityBody = true;
                    reply.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
                    return reply;
                }
            }

            string result = @"<?xml version=""1.0""?>
                                    <!DOCTYPE cross-domain-policy SYSTEM ""http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"">
                                    <cross-domain-policy>
                                        <allow-access-from domain=""*"" />
                                    </cross-domain-policy>";
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
            Message replyMessage = StreamMessageHelper.CreateMessage(MessageVersion.None, String.Empty, new MemoryStream(Encoding.UTF8.GetBytes(result)));
            HttpResponseMessageProperty replyProperty = new HttpResponseMessageProperty();
            replyProperty.StatusCode = System.Net.HttpStatusCode.OK;
            replyProperty.Headers[HttpResponseHeader.ContentType] = "text/xml;charset=utf-8";
            replyMessage.Properties.Add(HttpResponseMessageProperty.Name, replyProperty);
            return replyMessage;
        }
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            HttpResponseMessageProperty property = null;

            if (reply == null)
            {
                // This will usually be for a preflight response
                reply = Message.CreateMessage(MessageVersion.None, null);
                property = new HttpResponseMessageProperty();
                reply.Properties[HttpResponseMessageProperty.Name] = property;
                property.StatusCode = HttpStatusCode.OK;
            }
            else
            {
                property = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
            }

            PreflightDetected preflightRequest = OperationContext.Current.Extensions.Find<PreflightDetected>();
            if (preflightRequest != null)
            {
                // Add allow HTTP headers to respond to the preflight request
                if (preflightRequest.RequestedHeaders == string.Empty)
                    property.Headers.Add("Access-Control-Allow-Headers", "Accept");
                else
                    property.Headers.Add("Access-Control-Allow-Headers", preflightRequest.RequestedHeaders + ", Accept");

                property.Headers.Add("Access-Control-Allow-Methods", "*");

            }

            // Add allow-origin header to each response message, because client expects it
            if (property != null) property.Headers.Add("Access-Control-Allow-Origin", "*");
        }
        public override void ProcessRequest(ref System.ServiceModel.Channels.RequestContext requestContext)
        {
            var request = requestContext.RequestMessage;

            if (endpointFilter == null || endpointFilter(request))
            {
                IPrincipal principal = ExtractCredentials(request);
                if (principal != null)
                {
                    InitializeSecurityContext(request, principal);
                }
                else
                {
                    var reply = Message.CreateMessage(MessageVersion.None, null);
                    var responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };

                    if (sendChallenge)
                    {
                        var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();
                        var challenge = string.Format("ts=\"{0}\" ntp=\"{1}\"",
                            ts, "pool.ntp.org");

                        responseProperty.Headers.Add("WWW-Authenticate", challenge);
                    }

                    reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
                    requestContext.Reply(reply);

                    requestContext = null;
                }
            }
        }
예제 #12
0
    public override void ProcessRequest(ref RequestContext requestContext)
    {
      if (requestContext == null || requestContext.RequestMessage == null)
      {
        return;
      }

      Message request = requestContext.RequestMessage;

      var requestProperty = (HttpRequestMessageProperty) request.Properties[HttpRequestMessageProperty.Name];

      IOAuthContext context = new OAuthContextBuilder().FromUri(requestProperty.Method, request.Headers.To);

      try
      {
        _provider.AccessProtectedResourceRequest(context);

        AccessToken accessToken = _repository.GetToken(context.Token);

        TokenPrincipal principal = CreatePrincipalFromToken(accessToken);

        InitializeSecurityContext(request, principal);
      }
      catch (OAuthException authEx)
      {
        XElement response = GetHtmlFormattedErrorReport(authEx);
        Message reply = Message.CreateMessage(MessageVersion.None, null, response);
        var responseProperty = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.Forbidden, StatusDescription = authEx.Report.ToString()};
        responseProperty.Headers[HttpResponseHeader.ContentType] = "text/html";
        reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
        requestContext.Reply(reply);

        requestContext = null;
      }
    }
예제 #13
0
        Message HandlePreflight(Message input)
        {
            HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)input.Properties[HttpRequestMessageProperty.Name];
            string origin = httpRequest.Headers[CorsConstants.Origin];
            string requestMethod = httpRequest.Headers[CorsConstants.AccessControlRequestMethod];
            string requestHeaders = httpRequest.Headers[CorsConstants.AccessControlRequestHeaders];

            Message reply = Message.CreateMessage(MessageVersion.None, replyAction);
            HttpResponseMessageProperty httpResponse = new HttpResponseMessageProperty();
            reply.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);

            httpResponse.SuppressEntityBody = true;
            httpResponse.StatusCode = HttpStatusCode.OK;
            if (origin != null)
            {
                httpResponse.Headers.Add(CorsConstants.AccessControlAllowOrigin, origin);
            }

            if (requestMethod != null && this.allowedHttpMethods.Contains(requestMethod))
            {
                httpResponse.Headers.Add(CorsConstants.AccessControlAllowMethods, string.Join(",", this.allowedHttpMethods));
            }

            if (requestHeaders != null)
            {
                httpResponse.Headers.Add(CorsConstants.AccessControlAllowHeaders, requestHeaders);
            }

            return reply;
        }
예제 #14
0
        /// <summary>
        /// Enables the creation of a custom <see cref="System.ServiceModel.FaultException"/>
        /// that is returned from an exception in the course of a service method.
        /// </summary>
        /// <param name="error"></param>
        /// <param name="version"></param>
        /// <param name="faultMessage"></param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message faultMessage)
        {
            // Gets a serializable Fault object fromn error.
            Fault fault = Fault.GetFault(error);

            // Now we make the message by serializing the Fault to JSON.
            faultMessage = Message.CreateMessage(version, null, fault,
              new DataContractJsonSerializer(fault.GetType()));

            // Gotta set HTTP status codes.
            HttpResponseMessageProperty prop = new HttpResponseMessageProperty()
            {
                StatusCode = HttpStatusCode.InternalServerError, // 500
                StatusDescription = "An internal server error occurred." // Could use elaboration.
            };

            // Make sure to set the content type. Important for avoiding
            // certain kinds of encoding-specific XSS attacks.
            prop.Headers[HttpResponseHeader.ContentType] = "application/json; charset=utf-8";

            // Set a few other properties of the Message.
            faultMessage.Properties.Add(HttpResponseMessageProperty.Name, prop);
            faultMessage.Properties.Add(WebBodyFormatMessageProperty.Name,
                new WebBodyFormatMessageProperty(WebContentFormat.Json));
        }
 private static HttpResponseMessageProperty CreateResponseProperty(DigestHeader digestHeader)
 {
     var responseProperty = new HttpResponseMessageProperty();
      responseProperty.StatusCode = HttpStatusCode.Unauthorized;
      responseProperty.Headers.Add(DigestAuthenticationHeaderName, digestHeader.GenerateHeaderString());
      return responseProperty;
 }
예제 #16
0
 private static void AssignLogStatus(HttpResponseMessageProperty httpResp, Message reply, Log log)
 {
     string errorElement = log["SuccessElement"];
     if(string.IsNullOrEmpty(errorElement)) return;
     if (!log.Response.Contains(errorElement))
         log.Status = Status.Failure;
 }
예제 #17
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            var errorModel = new ErrorModel {Message = error.Message, Type = error.GetType().Name, Success = false};
            fault = Message.CreateMessage(version, null, errorModel, new DataContractJsonSerializer(typeof (ErrorModel)));
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));

            if (IsAuthenticationException(error))
            {
                var rmp = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.Unauthorized};
                rmp.StatusDescription = rmp.StatusCode.ToString();
                rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
                fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
            else if (error.GetType() == typeof (InvalidOperationException) || error.GetType() == typeof (ArgumentException))
            {
                var rmp = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.BadRequest};
                rmp.StatusDescription = rmp.StatusCode.ToString();
                rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
                fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
            else
            {
                errorModel.Message = "Unable to perform the operation";
                var rmp = new HttpResponseMessageProperty {StatusCode = HttpStatusCode.InternalServerError};
                rmp.StatusDescription = rmp.StatusCode.ToString();
                rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
                fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
        }
        public static void SetHttpResponseProperty(this Message message, HttpResponseMessageProperty httpResponse)
        {
            if (message.Properties.ContainsKey(HttpResponseMessageProperty.Name))
                message.Properties.Remove(HttpResponseMessageProperty.Name);

            message.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
        }
예제 #19
0
        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);
        }
예제 #20
0
 /// <summary>
 /// Provides the fault.
 /// </summary>
 /// <param name="error">The error.</param>
 /// <param name="version">The version.</param>
 /// <param name="fault">The fault.</param>
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     if (fault != null)
     {
         HttpResponseMessageProperty properties = new HttpResponseMessageProperty();
         properties.StatusCode = HttpStatusCode.InternalServerError;
         fault.Properties.Add(HttpResponseMessageProperty.Name, properties);
     }
 }
예제 #21
0
 public Message ProcessRequest(Message request)
 {
     Console.WriteLine("Server received a request from client");            
     HttpResponseMessageProperty httpResponseProperty = new HttpResponseMessageProperty();
     httpResponseProperty.Headers.Add("Content-Type", "application/octet-stream");
     request.Properties.Add(HttpResponseMessageProperty.Name, httpResponseProperty);
     Console.WriteLine("Server is sending back the same image to client");
     return request;
 }
예제 #22
0
 /// <summary>
 /// Get the HttpResponseMessageProperty 
 /// </summary>
 /// <param name="fault"></param>
 /// <param name="statusCode"></param>
 /// <param name="statusDescription"></param>
 protected virtual void ApplyHttpResponseSettings(ref Message fault, System.Net.HttpStatusCode statusCode, string statusDescription)
 {
     var httpResponse = new HttpResponseMessageProperty()
     {
         StatusCode = statusCode,
         StatusDescription = statusDescription
     };
     fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
 }
 /// <summary>
 /// Called after the operation has returned but before the reply message is sent.
 /// </summary>
 /// <param name="reply">The reply message. This value is null if the operation is one way.</param><param name="correlationState">The correlation object returned from the <see cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest(System.ServiceModel.Channels.Message@,System.ServiceModel.IClientChannel,System.ServiceModel.InstanceContext)"/> method.</param>
 public void BeforeSendReply(ref Message reply, object correlationState)
 {
     if (reply.IsFault)
     {
         var property = new HttpResponseMessageProperty();
         // Here the response code is changed to 200.
         property.StatusCode = HttpStatusCode.OK;
         reply.Properties[HttpResponseMessageProperty.Name] = property;
     }
 }
        void IDispatchMessageInspector.BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                HttpResponseMessageProperty property = new HttpResponseMessageProperty();
                property.StatusCode = System.Net.HttpStatusCode.OK; // 200

                reply.Properties[HttpResponseMessageProperty.Name] = property;
            }
        }
예제 #25
0
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     var realException = GetRealException(error);
     FaultException fe = new FaultException(realException.Message);
     MessageFault messageFault = fe.CreateMessageFault();
     fault = Message.CreateMessage(version, messageFault, "http://microsoft.wcf.documentation/default");
     HttpResponseMessageProperty property = new HttpResponseMessageProperty();
     property.StatusCode = System.Net.HttpStatusCode.OK;
     fault.Properties[HttpResponseMessageProperty.Name] = property;
 }
예제 #26
0
 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;
 }
예제 #27
0
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            var prop = new HttpResponseMessageProperty();
            prop.Headers.Add("Access-Control-Allow-Origin", "*");
            prop.Headers.Add("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
            prop.Headers.Add("Access-Control-Allow-Headers", "Content-Type, accept");

            operationContext.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, prop);
            return true;
        }
예제 #28
0
		IMessageProperty IMessageProperty.CreateCopy ()
		{
			var copy = new HttpResponseMessageProperty ();
			// FIXME: Clone headers?
			copy.headers = headers;
			copy.status_desc = status_desc;
			copy.status_code = status_code;
			copy.suppress_entity = suppress_entity;
			return copy;
		}
예제 #29
0
        public Message ProcessMessage(Message request)
        {
            Message response = null;

            //The HTTP Method (e.g. GET) from the incoming HTTP request
            //can be found on the HttpRequestMessageProperty. The MessageProperty
            //is added by the HTTP Transport when the message is received.
            HttpRequestMessageProperty requestProperties =
                (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

            //Here we dispatch to different internal implementation methods
            //based on the incoming HTTP verb.
            if (requestProperties != null)
            {
                if (String.Equals("GET", requestProperties.Method,
                    StringComparison.OrdinalIgnoreCase))
                {
                    response = GetCustomer(request);
                }
                else if (String.Equals("PUT", requestProperties.Method,
                    StringComparison.OrdinalIgnoreCase))
                {
                    response = UpdateCustomer(request);
                }
                else if (String.Equals("POST", requestProperties.Method,
                    StringComparison.OrdinalIgnoreCase))
                {
                    response = AddCustomer(request);
                }
                else if (String.Equals("DELETE", requestProperties.Method,
                    StringComparison.OrdinalIgnoreCase))
                {
                    response = DeleteCustomer(request);
                }
                else
                {
                    //This service doesn't implement handlers for other HTTP verbs (such as HEAD), so we
                    //construct a response message and use the HttpResponseMessageProperty to
                    //set the HTTP status code to 405 (Method Not Allowed) which indicates the client 
                    //used an HTTP verb not supported by the server.
                    response = Message.CreateMessage(MessageVersion.None, String.Empty, String.Empty);

                    HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty();
                    responseProperty.StatusCode = HttpStatusCode.MethodNotAllowed;

                    response.Properties.Add( HttpResponseMessageProperty.Name, responseProperty );
                }
            }
            else
            {
                throw new InvalidOperationException( "This service requires the HTTP transport" );
            }

            return response;
        }
예제 #30
0
        public Message CreateEmptyResponse()
        {
            Message response = Message.CreateMessage(MessageVersion.Default, null, (object)null);

            HttpResponseMessageProperty http = new HttpResponseMessageProperty();
            http.StatusCode = System.Net.HttpStatusCode.OK;
            http.SuppressEntityBody = true;
            response.Properties.Add(HttpResponseMessageProperty.Name, http);

            return response;
        }
            HttpResponseMessage CreateHttpResponseMessage(Message message)
            {
                HttpResponseMessage httpResponseMessage = HttpResponseMessageProperty.GetHttpResponseMessageFromMessage(message);

                if (httpResponseMessage == null)
                {
                    HttpResponseMessageProperty property = message.Properties.GetValue <HttpResponseMessageProperty>(HttpResponseMessageProperty.Name);
                    httpResponseMessage            = new HttpResponseMessage();
                    httpResponseMessage.StatusCode = message.IsFault ? HttpStatusCode.InternalServerError : HttpStatusCode.OK;
                    this.httpOutput.ConfigureHttpResponseMessage(message, httpResponseMessage, property);
                }

                return(httpResponseMessage);
            }
예제 #32
0
        private Message CreateAckMessage(HttpStatusCode statusCode, string statusDescription)
        {
            Message message = new NullMessage();
            HttpResponseMessageProperty property = new HttpResponseMessageProperty {
                StatusCode         = statusCode,
                SuppressEntityBody = true
            };

            if (statusDescription.Length > 0)
            {
                property.StatusDescription = statusDescription;
            }
            message.Properties.Add(HttpResponseMessageProperty.Name, property);
            return(message);
        }
            public HttpResponseMessageProperty CreateTraditionalResponseMessageProperty()
            {
                HttpResponseMessageProperty copiedProperty = new HttpResponseMessageProperty();

                copiedProperty.Headers.Add(this.Headers);

                if (this.StatusCode != TraditionalHttpResponseMessageProperty.DefaultStatusCode)
                {
                    copiedProperty.StatusCode = this.StatusCode;
                }

                copiedProperty.StatusDescription  = this.StatusDescription;
                copiedProperty.SuppressEntityBody = this.SuppressEntityBody;

                return(copiedProperty);
            }
예제 #34
0
        Message CreateAckMessage(HttpStatusCode statusCode, string statusDescription)
        {
            Message ackMessage = new NullMessage();
            HttpResponseMessageProperty httpResponseProperty = new HttpResponseMessageProperty();

            httpResponseProperty.StatusCode         = statusCode;
            httpResponseProperty.SuppressEntityBody = true;
            if (statusDescription.Length > 0)
            {
                httpResponseProperty.StatusDescription = statusDescription;
            }

            ackMessage.Properties.Add(HttpResponseMessageProperty.Name, httpResponseProperty);

            return(ackMessage);
        }
예제 #35
0
        protected override void ProcessReply(Message msg, TimeSpan timeout)
        {
            if (msg == null)
            {
                throw new ArgumentNullException("msg");
            }

            // FIXME: should this be done here?
            if (channel.MessageVersion.Addressing.Equals(AddressingVersion.None))
            {
                msg.Headers.Action = null;                 // prohibited
            }
            MemoryStream ms = new MemoryStream();

            channel.Encoder.WriteMessage(msg, ms);
            ctx.Response.ContentType = channel.Encoder.ContentType;

            string pname = HttpResponseMessageProperty.Name;
            bool   suppressEntityBody = false;

            if (msg.Properties.ContainsKey(pname))
            {
                HttpResponseMessageProperty hp = (HttpResponseMessageProperty)msg.Properties [pname];
                string contentType             = hp.Headers ["Content-Type"];
                if (contentType != null)
                {
                    ctx.Response.ContentType = contentType;
                }
                ctx.Response.Headers.Add(hp.Headers);
                if (hp.StatusCode != default(HttpStatusCode))
                {
                    ctx.Response.StatusCode = (int)hp.StatusCode;
                }
                ctx.Response.StatusDescription = hp.StatusDescription;
                if (hp.SuppressEntityBody)
                {
                    suppressEntityBody = true;
                }
            }
            if (!suppressEntityBody)
            {
                ctx.Response.ContentLength64 = ms.Length;
                ctx.Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
                ctx.Response.OutputStream.Flush();
            }
        }
        internal static HttpResponseMessage GetHttpResponseMessageFromMessage(Message message)
        {
            HttpResponseMessage httpResponseMessage = null;

            HttpResponseMessageProperty property = message.Properties.GetValue <HttpResponseMessageProperty>(HttpResponseMessageProperty.Name);

            if (property != null)
            {
                httpResponseMessage = property.HttpResponseMessage;
                if (httpResponseMessage != null)
                {
                    httpResponseMessage.CopyPropertiesFromMessage(message);
                    message.EnsureReadMessageState();
                }
            }

            return(httpResponseMessage);
        }
        void OnSendHttpCookies(Message message, ContextMessageProperty context, Uri requestUri)
        {
            object tmpProperty;
            HttpResponseMessageProperty property = null;

            if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out tmpProperty))
            {
                property = tmpProperty as HttpResponseMessageProperty;
            }
            if (property == null)
            {
                property = new HttpResponseMessageProperty();
                message.Properties.Add(HttpResponseMessageProperty.Name, property);
            }
            string setCookieHeader = HttpCookieToolbox.EncodeContextAsHttpSetCookieHeader(context, requestUri);

            property.Headers.Add(HttpResponseHeader.SetCookie, setCookieHeader);
        }
예제 #38
0
        protected override void ProcessReply(Message msg, TimeSpan timeout)
        {
            ctx.Response.ContentType = Channel.Encoder.ContentType;
            MemoryStream ms = new MemoryStream();

            Channel.Encoder.WriteMessage(msg, ms);

            string pname = HttpResponseMessageProperty.Name;
            bool   suppressEntityBody = false;

            if (msg.Properties.ContainsKey(pname))
            {
                HttpResponseMessageProperty hp = (HttpResponseMessageProperty)msg.Properties [pname];
                string contentType             = hp.Headers ["Content-Type"];
                if (contentType != null)
                {
                    ctx.Response.ContentType = contentType;
                }
                ctx.Response.Headers.Add(hp.Headers);
                if (hp.StatusCode != default(HttpStatusCode))
                {
                    ctx.Response.StatusCode = (int)hp.StatusCode;
                }
                ctx.Response.StatusDescription = hp.StatusDescription;
                if (hp.SuppressEntityBody)
                {
                    suppressEntityBody = true;
                }
            }
            if (msg.IsFault)
            {
                ctx.Response.StatusCode = 500;
            }
            if (!suppressEntityBody)
            {
                ctx.Response.AddHeader("Content-Length", ms.Length.ToString(CultureInfo.InvariantCulture));
                ctx.Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
                ctx.Response.OutputStream.Flush();
            }
            else
            {
                ctx.Response.SuppressContent = true;
            }
        }
예제 #39
0
            public bool SendResponse()
            {
                if (onSendCompleted == null)
                {
                    onSendCompleted = Fx.ThunkCallback(new AsyncCallback(OnSendResponseCompletedCallback));
                }

                bool success = false;

                try
                {
                    this.closeOutputAfterReply = context.PrepareReply(ref this.responseMessage);
                    if (onHttpPipelineSend == null)
                    {
                        onHttpPipelineSend = new Action <object, HttpResponseMessage>(OnHttpPipelineSendCallback);
                    }

                    if (context.httpPipeline.SendAsyncReply(this.responseMessage, onHttpPipelineSend, this) == AsyncCompletionResult.Queued)
                    {
                        //// In Async send + HTTP pipeline path, we will send the response back after the result coming out from the pipeline.
                        //// So we don't need to call it here.
                        success = true;
                        return(false);
                    }

                    HttpResponseMessage httpResponseMessage = null;

                    if (this.context.HttpMessagesSupported)
                    {
                        httpResponseMessage = HttpResponseMessageProperty.GetHttpResponseMessageFromMessage(this.responseMessage);
                    }

                    return(this.SendResponseCore(httpResponseMessage, out success));
                }
                finally
                {
                    if (!success && this.message != null &&
                        !object.ReferenceEquals(this.message, this.responseMessage))
                    {
                        this.responseMessage.Close();
                    }
                }
            }
            public HttpResponseMessageProperty CreateTraditionalResponseMessageProperty()
            {
                HttpResponseMessageProperty copiedProperty = new HttpResponseMessageProperty();

                foreach (var headerKey in this.Headers.AllKeys)
                {
                    copiedProperty.Headers[headerKey] = this.Headers[headerKey];
                }

                if (this.StatusCode != TraditionalHttpResponseMessageProperty.DefaultStatusCode)
                {
                    copiedProperty.StatusCode = this.StatusCode;
                }

                copiedProperty.StatusDescription  = this.StatusDescription;
                copiedProperty.SuppressEntityBody = this.SuppressEntityBody;

                return(copiedProperty);
            }
            protected override void SendReplyCore(Message message, TimeSpan timeout)
            {
                this.TraceProcessResponseStart();
                ThreadTrace.Trace("Begin sending http reply");
                HttpOutput httpOutput = this.GetHttpOutput(message);

                HttpResponseMessage response = HttpResponseMessageProperty.GetHttpResponseMessageFromMessage(message);

                if (response != null)
                {
                    httpOutput.Send(response, timeout);
                }
                else
                {
                    httpOutput.Send(timeout);
                }

                ThreadTrace.Trace("End sending http reply");
                this.TraceProcessResponseStop();
            }
예제 #42
0
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (DEBUG && correlationState != null)
            {
                QZ.RealTimeRequestLogService.RequestLog rt = (QZ.RealTimeRequestLogService.RequestLog)correlationState;
                TimeSpan ts = DateTime.Now - rt.Time;
                rt.TotalSpend = ts.Milliseconds;

                if (reply != null)
                {
                    MessageProperties mp = reply.Properties;

                    object obj;

                    if (mp.TryGetValue("httpResponse", out obj))
                    {
                        System.ServiceModel.Channels.HttpResponseMessageProperty wh = (System.ServiceModel.Channels.HttpResponseMessageProperty)obj;
                        rt.ResponseHeader      = wh.Headers.ToString();
                        rt.ResponseContentType = wh.Headers[System.Net.HttpResponseHeader.ContentType];
                        rt.ResponseStatusCode  = (int)wh.StatusCode;
                        rt.ResponseStatusStr   = wh.StatusCode.ToString();
                    }

                    if (rt.ResponseStatusCode == 200)
                    {
                        rt.Response = GetReponseBody(reply);
                    }
                    else
                    {
                        rt.Response = string.Empty;
                    }
                }
                else
                {
                    rt.ResponseStatusStr = "no reply message captured, unable to read the response infomation.";
                }
                QZ.RealTimeRequestLogService.RealTimeRequestLog.AppendLog(rt);
            }
        }
예제 #43
0
        void GotResponse(IAsyncResult result)
        {
            HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult)result.AsyncState;

            channelResult.CompletedSynchronously &= result.CompletedSynchronously;

            WebResponse res;
            Stream      resstr;

            try
            {
                res    = channelResult.WebRequest.EndGetResponse(result);
                resstr = res.GetResponseStream();
            }
            catch (WebException we)
            {
                res = we.Response;
                if (res == null)
                {
                    channelResult.Complete(we);
                    return;
                }


                var hrr2 = (HttpWebResponse)res;

                if ((int)hrr2.StatusCode >= 400 && (int)hrr2.StatusCode < 500)
                {
                    Exception exception = new WebException(
                        String.Format("There was an error on processing web request: Status code {0}({1}): {2}",
                                      (int)hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null,
                        WebExceptionStatus.ProtocolError, hrr2);

                    if ((int)hrr2.StatusCode == 404)
                    {
                        // Throw the same exception .NET does
                        exception = new EndpointNotFoundException(
                            "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " +
                            "or SOAP action. See InnerException, if present, for more details.",
                            exception);
                    }

                    channelResult.Complete(exception);
                    return;
                }


                try
                {
                    // The response might contain SOAP fault. It might not.
                    resstr = res.GetResponseStream();
                }
                catch (WebException we2)
                {
                    channelResult.Complete(we2);
                    return;
                }
            }

            var hrr = (HttpWebResponse)res;

            if ((int)hrr.StatusCode >= 400 && (int)hrr.StatusCode < 500)
            {
                channelResult.Complete(new WebException(String.Format("There was an error on processing web request: Status code {0}({1}): {2}", (int)hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
            }

            try
            {
                Message ret;

                // TODO: unit test to make sure an empty response never throws
                // an exception at this level
                if (hrr.ContentLength == 0)
                {
                    ret = Message.CreateMessage(Encoder.MessageVersion, String.Empty);
                }
                else
                {
                    using (var responseStream = resstr)
                    {
                        MemoryStream ms = new MemoryStream();
                        byte []      b  = new byte [65536];
                        int          n  = 0;

                        while (true)
                        {
                            n = responseStream.Read(b, 0, 65536);
                            if (n == 0)
                            {
                                break;
                            }
                            ms.Write(b, 0, n);
                        }
                        ms.Seek(0, SeekOrigin.Begin);

                        ret = Encoder.ReadMessage(
                            ms, (int)source.Transport.MaxReceivedMessageSize, res.ContentType);
                    }
                }

                var rp = new HttpResponseMessageProperty()
                {
                    StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription
                };
#if MOONLIGHT
                if (hrr.SupportsHeaders)
                {
                    foreach (string key in hrr.Headers)
                    {
                        rp.Headers [key] = hrr.Headers [key];
                    }
                }
#else
                foreach (var key in hrr.Headers.AllKeys)
                {
                    rp.Headers [key] = hrr.Headers [key];
                }
#endif
                ret.Properties.Add(HttpResponseMessageProperty.Name, rp);

                channelResult.Response = ret;
                channelResult.Complete();
            }
            catch (Exception ex)
            {
                channelResult.Complete(ex);
            }
            finally
            {
                res.Close();
            }
        }
예제 #44
0
        protected override void ProcessReply(Message msg, TimeSpan timeout)
        {
            if (msg == null)
            {
                throw new ArgumentNullException("msg");
            }

            // Handle DestinationUnreacheable as 400 (it is what .NET does).
            if (msg.IsFault)
            {
                // FIXME: isn't there any better way?
                var mb    = msg.CreateBufferedCopy(0x10000);
                var fault = MessageFault.CreateFault(mb.CreateMessage(), 0x10000);
                if (fault.Code.Name == "DestinationUnreachable")
                {
                    ctx.Response.StatusCode = 400;
                    return;
                }
                else
                {
                    msg = mb.CreateMessage();
                }
            }

            // FIXME: should this be done here?
            if (channel.MessageVersion.Addressing.Equals(AddressingVersion.None))
            {
                msg.Headers.Action = null;                 // prohibited
            }
            MemoryStream ms = new MemoryStream();

            channel.Encoder.WriteMessage(msg, ms);
            ctx.Response.ContentType = channel.Encoder.ContentType;

            string pname = HttpResponseMessageProperty.Name;
            bool   suppressEntityBody = false;

            if (msg.Properties.ContainsKey(pname))
            {
                HttpResponseMessageProperty hp = (HttpResponseMessageProperty)msg.Properties [pname];
                string contentType             = hp.Headers ["Content-Type"];
                if (contentType != null)
                {
                    ctx.Response.ContentType = contentType;
                }
                ctx.Response.Headers.Add(hp.Headers);
                if (hp.StatusCode != default(HttpStatusCode))
                {
                    ctx.Response.StatusCode = (int)hp.StatusCode;
                }
                ctx.Response.StatusDescription = hp.StatusDescription;
                if (hp.SuppressEntityBody)
                {
                    suppressEntityBody = true;
                }
            }
            if (!suppressEntityBody)
            {
                ctx.Response.ContentLength64 = ms.Length;
                ctx.Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
                ctx.Response.OutputStream.Flush();
            }
        }