示例#1
0
            public static string WriteEndpointInterface(HttpEndpoint endpoint)
            {
                return
                    ($@"
{SharedWriter.GetObsolete(endpoint)}
{GetInterfaceReturnType(endpoint.ReturnType, false)} {endpoint.Name}
(
{string.Join($",{Environment.NewLine}", endpoint.GetParameters().Select(SharedWriter.GetParameter))}
);

{SharedWriter.GetObsolete(endpoint)}
{GetInterfaceReturnType(nameof(HttpResponseMessage), false)} {endpoint.Name}Raw
(
{string.Join($",{Environment.NewLine}", endpoint.GetParametersWithoutResponseTypes().Select(SharedWriter.GetParameter))}
);

{SharedWriter.GetObsolete(endpoint)}
{GetInterfaceReturnType(endpoint.ReturnType, true)} {endpoint.Name}Async
(
{string.Join($",{Environment.NewLine}", endpoint.GetParameters().Select(SharedWriter.GetParameter))}
);

{SharedWriter.GetObsolete(endpoint)}
{GetInterfaceReturnType(nameof(HttpResponseMessage), true)} {endpoint.Name}RawAsync
(
{string.Join($",{Environment.NewLine}", endpoint.GetParametersWithoutResponseTypes().Select(SharedWriter.GetParameter))}
);

");
            }
示例#2
0
        public async Task ThrowServiceException()
        {
            // arrange
            var exception = default(Exception);

            _endpoint = new HttpEndpoint
            {
                BaseAddress = "http://not-found.de/123",
                Request     = "",
                MethodName  = ""
            };

            // act
            try
            {
                _service = new GenericService(new HttpClient(), _endpoint);
                _service.CallResponded += (o, e) =>
                {
                    Log.Info($"Http responded with code: {e.StatusCode}");
                };
                var result = await _service.CallAsync <object>((s) => JsonIO.FromJsonString <object>(s));
            }
            catch (Exception ex)
            {
                Log.Fatal(ex);
                exception = ex;
            }

            // assert
            Assert.IsNotNull(exception);
        }
            public IEnumerator <object[]> GetEnumerator()
            {
                // http
                yield return(new object[] { $"endpoint={HttpEndpoint};accesskey={DefaultKey}", HttpEndpoint, HttpEndpoint });

                yield return(new object[] { $"endpoint={HttpEndpoint}:80;accesskey={DefaultKey}", HttpEndpoint, HttpEndpoint });

                yield return(new object[] { $"endpoint={HttpEndpoint}:500;accesskey={DefaultKey}", HttpEndpoint, HttpEndpoint + ":500" });

                // https
                yield return(new object[] { $"endpoint={HttpsEndpoint};accesskey={DefaultKey}", HttpsEndpoint, HttpsEndpoint });

                yield return(new object[] { $"endpoint={HttpsEndpoint}:443;accesskey={DefaultKey}", HttpsEndpoint, HttpsEndpoint });

                yield return(new object[] { $"endpoint={HttpsEndpoint}:500;accesskey={DefaultKey}", HttpsEndpoint, HttpsEndpoint + ":500" });

                // uppercase endpoint
                yield return(new object[] { $"endpoint={HttpEndpoint.ToUpper()};accesskey={DefaultKey}", HttpEndpoint, HttpEndpoint });

                yield return(new object[] { $"endpoint={HttpsEndpoint.ToUpper()};accesskey={DefaultKey}", HttpsEndpoint, HttpsEndpoint });

                // port override
                yield return(new object[] { $"endpoint={HttpsEndpoint};accesskey={DefaultKey};port=500", HttpsEndpoint, HttpsEndpoint + ":500" });

                yield return(new object[] { $"endpoint={HttpsEndpoint}:500;accesskey={DefaultKey};port=443", HttpsEndpoint, HttpsEndpoint });

                // uppercase property name
                yield return(new object[] { $"ENDPOINT={HttpEndpoint};ACCESSKEY={DefaultKey}", HttpEndpoint, HttpEndpoint });

                yield return(new object[] { $"ENDPOINT={HttpsEndpoint}:500;ACCESSKEY={DefaultKey};PORT=443", HttpsEndpoint, HttpsEndpoint });
            }
示例#4
0
        public void ArtifactScenario_GetArtifactsFromXY_Json_MediaRange()
        {
            string baseAddress = string.Format("http://localhost:{0}", GetNextPortNumber());

            MediaTypeHeaderValue range           = new MediaTypeHeaderValue("text/*");
            MediaTypeHeaderValue mapsToMediaType = new MediaTypeHeaderValue("text/json");

            using (HttpServiceHost host = CreateHttpServiceHost(typeof(ArtifactService), baseAddress, range, mapsToMediaType))
            {
                HttpEndpoint endPoint = host.Description.Endpoints.OfType <HttpEndpoint>().Single();

                // Add a media range mapping to map text/* to text/json
                //endPoint.MediaTypeMappings.Add(new MediaRangeMapping("text/*", "text/json"));

                host.Open();

                using (HttpClient client = new HttpClient())
                {
                    client.Channel = new WebRequestChannel();
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, baseAddress + "/Artifacts/5,6");
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/*"));
                    using (HttpResponseMessage response = client.Send(request))
                    {
                        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "status code not ok");
                        Artifact[] artifacts = DeserializeArtifactsJson(response);
                        Assert.AreEqual(2, artifacts.Length, "Expected 2 artifacts at pos 5,6");
                        foreach (Artifact artifact in artifacts)
                        {
                            Assert.AreEqual(5, artifact.GridPosition.X, "gridX should be 5");
                            Assert.AreEqual(6, artifact.GridPosition.Y, "gridY should be 5");
                        }
                    }
                }
            }
        }
示例#5
0
        /// <summary>
        /// Called when a new HTTP request is received
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <returns>Asynchronous task</returns>
        public async Task InvokeAsync(HttpContext context)
        {
            // Check if this endpoint is reserved for any route
            HttpEndpoint httpEndpoint = null;

            lock (Services.ModelObserver.Endpoints)
            {
                string method = context.WebSockets.IsWebSocketRequest ? "WebSocket" : context.Request.Method.ToString();
                if (Services.ModelObserver.Endpoints.TryGetValue($"{method}{context.Request.Path.Value}", out HttpEndpoint ep))
                {
                    httpEndpoint = ep;
                }
                else
                {
                    _logger.LogInformation("No endpoint found for {0} request via {1}", method, context.Request.Path.Value);
                }
            }

            if (httpEndpoint != null)
            {
                // Try to connect to the given UNIX socket
                using HttpEndpointConnection endpointConnection = new HttpEndpointConnection();
                endpointConnection.Connect(httpEndpoint.UnixSocket);

                // Try to find a user session
                int sessionId = -1;
                lock (Services.ModelObserver.UserSessions)
                {
                    string ipAddress = context.Connection.RemoteIpAddress.ToString();
                    if (Services.ModelObserver.UserSessions.TryGetValue(ipAddress, out int foundSessionId))
                    {
                        sessionId = foundSessionId;
                    }
                }

                // See what to do with this request
                if (httpEndpoint.EndpointType == HttpEndpointType.WebSocket)
                {
                    using WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                    using CancellationTokenSource cts = new CancellationTokenSource();
                    Task webSocketTask  = ReadFromWebSocket(webSocket, endpointConnection, sessionId, cts.Token);
                    Task unixSocketTask = ReadFromUnixSocket(webSocket, endpointConnection, cts.Token);

                    await Task.WhenAny(webSocketTask, unixSocketTask);

                    cts.Cancel();
                }
                else
                {
                    await ProcessRestRequst(context, endpointConnection, sessionId);
                }
            }
            else
            {
                // Call the next delegate/middleware in the pipeline
                await _next(context);
            }
        }
示例#6
0
        private static HttpServiceHost CreateHttpServiceHost(Type serviceType, string baseAddress)
        {
            HttpServiceHost host = new HttpServiceHost(serviceType, new Uri(baseAddress));

            host.AddDefaultEndpoints();
            HttpEndpoint endpoint = host.Description.Endpoints.OfType <HttpEndpoint>().Single();

            endpoint.OperationHandlerFactory = new ArtifactHttpOperationHandlerFactory(new MediaTypeFormatter[0]);
            return(host);
        }
示例#7
0
        private static HttpServiceHost CreateHttpServiceHost(Type serviceType, string baseAddress, MediaTypeHeaderValue range, MediaTypeHeaderValue mediaType)
        {
            HttpServiceHost host = new HttpServiceHost(serviceType, new Uri(baseAddress));

            host.AddDefaultEndpoints();
            HttpEndpoint endpoint = host.Description.Endpoints.OfType <HttpEndpoint>().Single();
            MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection();

            formatters.JsonFormatter.AddMediaRangeMapping(range, mediaType);
            endpoint.OperationHandlerFactory = new ArtifactHttpOperationHandlerFactory(formatters);
            return(host);
        }
示例#8
0
        public void ServiceHost_Explicit_Add_Endpoint_Without_Behavior()
        {
            ContractDescription cd       = ContractDescription.GetContract(typeof(LocalCustomerService));
            HttpServiceHost     host     = new HttpServiceHost(typeof(LocalCustomerService), new Uri("http://localhost"));
            HttpEndpoint        endpoint = new HttpEndpoint(cd, new EndpointAddress("http://somehost"));

            endpoint.Behaviors.Clear();
            Assert.AreEqual(0, endpoint.Behaviors.Count, "Expected no behaviors by default");
            host.Description.Endpoints.Add(endpoint);
            host.Open();
            Assert.AreEqual(1, endpoint.Behaviors.OfType <HttpBehavior>().Count(), "Expected open to add behavior");
        }
示例#9
0
            public static string WriteErrorActionResultReturn(HttpEndpoint endpoint, bool async, bool raw)
            {
                if (raw)
                {
                    return(@"return null;");
                }

                if (endpoint.ReturnType != null)
                {
                    return($@"return default({endpoint.ReturnType});");
                }

                return("return;");
            }
示例#10
0
        private void InternalOnApplyConfiguration(ServiceEndpoint endpoint)
        {
            HttpEndpoint httpEndpoint = endpoint as HttpEndpoint;

            Fx.Assert(httpEndpoint != null, "The endpoint should be of type httpEndpoint since this is what was returned with CreateServiceEndpoint().");

            if (this.IsSet(HttpConfigurationStrings.HelpEnabled))
            {
                httpEndpoint.HelpEnabled = this.HelpEnabled;
            }

            if (this.IsSet(HttpConfigurationStrings.TrailingSlashMode))
            {
                httpEndpoint.TrailingSlashMode = this.TrailingSlashMode;
            }

            if (this.IsSet(HttpConfigurationStrings.OperationHandlerFactory))
            {
                httpEndpoint.OperationHandlerFactory = HttpBehaviorElement.GetHttpOperationHandlerFactory(this.OperationHandlerFactory);
            }

            if (this.IsSet(ConfigurationStrings.HostNameComparisonMode))
            {
                httpEndpoint.HostNameComparisonMode = this.HostNameComparisonMode;
            }

            if (this.IsSet(ConfigurationStrings.MaxBufferPoolSize))
            {
                httpEndpoint.MaxBufferPoolSize = this.MaxBufferPoolSize;
            }

            if (this.IsSet(ConfigurationStrings.MaxBufferSize))
            {
                httpEndpoint.MaxBufferSize = this.MaxBufferSize;
            }

            if (this.IsSet(ConfigurationStrings.MaxReceivedMessageSize))
            {
                httpEndpoint.MaxReceivedMessageSize = this.MaxReceivedMessageSize;
            }

            if (this.IsSet(ConfigurationStrings.TransferMode))
            {
                httpEndpoint.TransferMode = this.TransferMode;
            }

            this.Security.ApplyConfiguration(httpEndpoint.Security);
        }
示例#11
0
        private ServiceEndpoint GenerateDefaultServiceEndpoint(Uri baseAddress)
        {
            if (this.ImplementedContracts.Count != 1)
            {
                throw new InvalidOperationException(SR.DefaultEndpointsServiceWithMultipleContracts(this.Description.Name, httpServiceHostTypeName));
            }

            ContractDescription contractDescription = this.ImplementedContracts.Values.First();

            HttpEndpoint endpoint = new HttpEndpoint(contractDescription, new EndpointAddress(baseAddress));

            endpoint.MessageHandlerFactory   = this.MessageHandlerFactory;
            endpoint.OperationHandlerFactory = this.OperationHandlerFactory;

            return(endpoint);
        }
 protected override void OnConfigureEndpoint(HttpEndpoint endpoint)
 {
     foreach (var op in endpoint.Contract.Operations)
     {
         var bh = op.Behaviors.Find <WebGetAttribute>();
         if (bh == null)
         {
             continue;
         }
         string template = null;
         if (_map.TryGetValue(op.SyncMethod, out template))
         {
             bh.UriTemplate = template;
         }
     }
     base.OnConfigureEndpoint(endpoint);
 }
 /// <summary>
 /// Remove a third-party HTTP endpoint
 /// </summary>
 /// <returns>True if the endpint could be removed</returns>
 public override async Task <bool> Execute()
 {
     using (await Model.Provider.AccessReadWriteAsync())
     {
         for (int i = 0; i < Model.Provider.Get.HttpEndpoints.Count; i++)
         {
             HttpEndpoint ep = Model.Provider.Get.HttpEndpoints[i];
             if (ep.EndpointType == EndpointType && ep.Namespace == Namespace && ep.Path == Path)
             {
                 _logger.Debug("Removed HTTP endpoint {0} machine/{1}/{2}", EndpointType, Namespace, Path);
                 Model.Provider.Get.HttpEndpoints.RemoveAt(i);
                 return(true);
             }
         }
     }
     return(false);
 }
示例#14
0
        /// <summary>
        /// Add a new HTTP endpoint
        /// </summary>
        /// <returns>Reserved file path to a UNIX socket</returns>
        public override async Task <string> Execute()
        {
            // Check if the namespace is reserved
            if (Namespace == "file" || Namespace == "fileinfo" || Namespace == "directory")
            {
                throw new ArgumentException("Namespace is reserved");
            }

            // Check if the requested HTTP endpoint has already been registered. If yes, it may be reused
            using (await Model.Provider.AccessReadOnlyAsync())
            {
                foreach (HttpEndpoint endpoint in Model.Provider.Get.HttpEndpoints)
                {
                    if (endpoint.EndpointType == EndpointType && endpoint.Namespace == Namespace && endpoint.Path == Path)
                    {
                        if (IsUnixSocketAlive(endpoint.UnixSocket))
                        {
                            throw new InvalidOperationException("Requested HTTP endpoint is already registered and active");
                        }
                        return(endpoint.UnixSocket);
                    }
                }
            }

            // Create a UNIX socket file like /var/run/dsf/mynamespace/myaction-GET.sock
            string socketPath = System.IO.Path.Combine(Settings.SocketDirectory, Namespace, $"{Path}-{EndpointType}.sock");

            Directory.CreateDirectory(System.IO.Path.GetDirectoryName(socketPath));
            // NB: In case plugins are running as a separate user, the file has to be created here and the permissions have to be updated

            using (await Model.Provider.AccessReadWriteAsync())
            {
                HttpEndpoint endpoint = new HttpEndpoint();
                Model.Provider.Get.HttpEndpoints.Add(endpoint);

                endpoint.EndpointType    = EndpointType;
                endpoint.Namespace       = Namespace;
                endpoint.Path            = Path;
                endpoint.IsUploadRequest = IsUploadRequest;
                endpoint.UnixSocket      = socketPath;
            }

            _logger.Debug("Registered new HTTP endpoint {0} machine/{1}/{2} via {3}", EndpointType, Namespace, Path, socketPath);
            return(socketPath);
        }
示例#15
0
        public void Endpoint_Configured_Endpoint_From_ServiceHost()
        {
            ConfigAssert.Execute("Microsoft.ApplicationServer.Http.CIT.Unit.ConfiguredHttpEndpointWithServiceTest.config", () =>
            {
                HttpEndpoint[] endPoints = GetEndpointsFromServiceHost(typeof(CustomerService), new Uri("http://somehost"));
                Assert.IsTrue(endPoints.Length > 0, "No HttpEndpoints");
                HttpEndpoint endPoint = endPoints[0];
                Assert.AreEqual("HttpBinding_CustomerService", endPoint.Name, "Should have had this name");
                Assert.AreEqual(HostNameComparisonMode.Exact, endPoint.HostNameComparisonMode, "HostNameComparisonMode was not set");

                Assert.IsFalse(endPoint.HelpEnabled, "HelpEnabled wrong");
                Assert.AreEqual(TransferMode.Streamed, endPoint.TransferMode, "TransferMode wrong");
                Assert.AreEqual(HostNameComparisonMode.Exact, endPoint.HostNameComparisonMode, "HostNameComparisonMode wrong");
                Assert.AreEqual(1, endPoint.MaxBufferPoolSize, "MaxBufferPoolSize wrong");
                Assert.AreEqual(2, endPoint.MaxBufferSize, "MaxBufferSize wrong");
                Assert.AreEqual(3, endPoint.MaxReceivedMessageSize, "MaxReceivedMessageSize wrong");
            });
        }
示例#16
0
            public static string GetRoute(HttpController controller, HttpEndpoint endpoint, bool async)
            {
                const string RouteParseRegex = @"{([^}]+)}";

                string routeUnformatted = endpoint.GetFullRoute(controller);

                var patterns = Regex.Matches(routeUnformatted, RouteParseRegex);

                var routeParameters = endpoint.GetRouteParameters().ToList();
                var queryParameters = endpoint.GetQueryParameters().ToList();

                foreach (var group in patterns)
                {
                    Match    match    = group as Match;
                    string   filtered = match.Value.Replace("{", "").Replace("}", "");
                    string[] split    = filtered.Split(new char[] { ':' });

                    string variable = split[0];


                    if (!routeParameters.Any(x => x.Name.Equals(variable, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        throw new Exception($"{variable} is missing from passed in parameters. Please check your route.");
                    }
                    var parameter = routeParameters.SingleOrDefault(x => x.Name.Equals(variable, StringComparison.CurrentCultureIgnoreCase));
                    if (Helpers.IsRoutableType(parameter.Type))
                    {
                        routeUnformatted = routeUnformatted.Replace(match.Value, $"{{{Helpers.GetRouteStringTransform(parameter.Name, parameter.Type)}}}");
                    }
                }

                if (queryParameters.Any())
                {
                    string queryString = $"?{string.Join("&", queryParameters.Select(x => WriteQueryParameter(x, async)))}";

                    routeUnformatted += $"{queryString}";
                }



                routeUnformatted = routeUnformatted.Replace($"[{Constants.ControllerRouteReserved}]", $"{{{Constants.ControllerRouteReserved}}}");
                routeUnformatted = routeUnformatted.Replace($"[{Constants.ActionRouteReserved}]", $"{{{Constants.ActionRouteReserved}}}");
                return(routeUnformatted);
            }
示例#17
0
    private static IServiceCollection TryAddHttpEndpoint(
        this IServiceCollection services,
        HttpEndpoint fieldEndpoint)
    {
        foreach (var service in services)
        {
            if (service.ServiceType == typeof(HttpEndpoint))
            {
                var endpoint = (HttpEndpoint)service.ImplementationInstance !;
                if (endpoint.Pattern == fieldEndpoint.Pattern && endpoint.Method == fieldEndpoint.Method)
                {
                    return(services);
                }
            }
        }

        services.AddSingleton(fieldEndpoint);
        return(services);
    }
示例#18
0
            public static string GetMethodDetails(HttpController controller, HttpEndpoint endpoint, bool async, bool raw)
            {
                var cancellationToken = endpoint.GetRequestModifiers().OfType <CancellationTokenModifier>().SingleOrDefault();
                var clientDependency  = new ClientDependency($"I{Settings.ClientInterfaceName}Wrapper");

                var requestModifiers = endpoint.GetRequestModifiers().ToList();

                var    bodyParameter = endpoint.GetBodyParameter();
                string bodyVariable  = bodyParameter?.Name ?? "null";

                var responseTypes = endpoint.GetResponseTypes();

                var routeConstraints = endpoint.GetRouteConstraints(controller);

                return
                    ($@"{string.Join(Environment.NewLine, routeConstraints.Select(WriteRouteConstraint).NotNull())}
{GetEndpointInfoVariables(controller, endpoint)}
string url = $@""{GetRoute(controller, endpoint, async)}"";
HttpResponseMessage response = null;
response = {GetAwait(async)}HttpOverride.GetResponseAsync({GetHttpMethod(endpoint.HttpType)}, url, null, {cancellationToken.Name}){GetAsyncEnding(async)};

if(response == null)
{{
	try
	{{
		response = {GetAwait(async)}{clientDependency.GetDependencyName($"I{Settings.ClientInterfaceName}")}.{nameof(IClientWrapper.ClientWrapper)}
					.Request(url)
{string.Join($"				{Environment.NewLine}", requestModifiers.Select(WriteRequestModifiers).NotNull())}
					.AllowAnyHttpStatus()
					{GetHttpMethod(endpoint)}
					{GetAsyncEnding(async)};
	}}
	catch({nameof(FlurlHttpException)} fhex)
	{{
{WriteResponseType(responseTypes.OfType<ExceptionResponseType>().Single(), async, false)}
{WriteErrorActionResultReturn(endpoint, async, raw)}
	}}

	{GetAwait(async)}HttpOverride.OnNonOverridedResponseAsync({GetHttpMethod(endpoint.HttpType)}, url, {bodyVariable}, response, {cancellationToken.Name}){GetAsyncEnding(async)};
}}
{string.Join(Environment.NewLine, responseTypes.Where(x => x.GetType() != typeof(ExceptionResponseType)).Select(x => WriteResponseType(x, async, raw)).NotNull())}
{WriteActionResultReturn(endpoint, async, raw)}");
            }
示例#19
0
            public static string WriteActionResultReturn(HttpEndpoint endpoint, bool async, bool raw)
            {
                if (raw)
                {
                    return(@"return response;");
                }

                if (endpoint.ReturnsStream)
                {
                    return
                        ($@"
if(response.IsSuccessStatusCode)
{{
	return {GetAwait(async)}response.Content.ReadAsStreamAsync(){GetAsyncEnding(async)};
}}
else
{{
	return default({endpoint.ReturnType});
}}
");
                }
                else
                {
                    if (endpoint.ReturnType != null)
                    {
                        return
                            ($@"
if(response.IsSuccessStatusCode)
{{
	return {GetAwait(async)}Serializer.Deserialize<{endpoint.ReturnType}>(response.Content){GetAsyncEnding(async)};
}}
else
{{
	return default({endpoint.ReturnType});
}}
");
                    }
                }



                return("return;");
            }
示例#20
0
            public static string GetHttpMethod(HttpEndpoint endpoint)
            {
                var cancellationToken = endpoint.GetRequestModifiers().OfType <CancellationTokenModifier>().SingleOrDefault();
                var bodyParameter     = endpoint.GetBodyParameter();

                string bodyString = null;

                if (bodyParameter?.Name == null)
                {
                    bodyString = "null";
                }
                else
                {
                    bodyString = $@"Serializer.Serialize({bodyParameter?.Name})";
                }

                if (endpoint.HttpType.Method == HttpMethod.Delete.Method)
                {
                    return($".{nameof(GeneratedExtensions.DeleteAsync)}({cancellationToken?.Name})");
                }
                else if (endpoint.HttpType.Method == HttpMethod.Get.Method)
                {
                    return($".{nameof(GeneratedExtensions.GetAsync)}({cancellationToken?.Name})");
                }
                else if (endpoint.HttpType.Method == HttpMethod.Put.Method)
                {
                    return($".{nameof(GeneratedExtensions.PutAsync)}({bodyString}, {cancellationToken?.Name})");
                }
                else if (endpoint.HttpType.Method == new HttpMethod("PATCH").Method)
                {
                    return($".{nameof(GeneratedExtensions.PatchAsync)}({bodyString}, {cancellationToken?.Name})");
                }
                else if (endpoint.HttpType.Method == HttpMethod.Post.Method)
                {
                    return($".{nameof(GeneratedExtensions.PostAsync)}({bodyString}, {cancellationToken?.Name})");
                }
                else
                {
                    return($"#error Unsupported HttpMethod of {endpoint.HttpType.Method}");
                }
            }
示例#21
0
            public static string GetEndpointInfoVariables(HttpController controller, HttpEndpoint endpoint)
            {
                var controllerVar = $@"var {Constants.ControllerRouteReserved} = ""{endpoint.Parent.Name}"";";
                var actionVar     = $@"var {Constants.ActionRouteReserved} = ""{endpoint.Name}"";";


                if (!endpoint.GetFullRoute(controller).Contains($"[{Constants.ControllerRouteReserved}]"))
                {
                    controllerVar = null;
                }

                if (!endpoint.GetFullRoute(controller).Contains($"[{Constants.ActionRouteReserved}]"))
                {
                    actionVar = null;
                }


                return
                    ($@"{controllerVar}
{actionVar}");
            }
示例#22
0
        public async Task ServiceCallAsync()
        {
            // arrange
            _endpoint = new HttpEndpoint
            {
                BaseAddress = "https://api.abalin.net",
                Request     = "/get/today?country=de",
                MethodName  = "get"
            };
            _service = new GenericService(new HttpClient(), _endpoint);
            _service.CallResponded += (o, e) =>
            {
                Log.Info($"Http responded with code: {e.StatusCode}");
            };

            // act
            var result = await _service.CallAsync <object>((s) => JsonIO.FromJsonString <object>(s));

            // assert
            Assert.IsNotNull(result);
        }
        public AssetAdministrationShellHttpClient(IAssetAdministrationShellDescriptor aasDescriptor) : this()
        {
            aasDescriptor = aasDescriptor ?? throw new ArgumentNullException(nameof(aasDescriptor));
            HttpEndpoint httpEndpoint = aasDescriptor.Endpoints?.OfType <HttpEndpoint>()?.FirstOrDefault();

            if (httpEndpoint == null || string.IsNullOrEmpty(httpEndpoint.Address))
            {
                throw new Exception("There is no http endpoint for instantiating a client");
            }
            else
            {
                if (!httpEndpoint.Address.EndsWith(SEPARATOR + AAS) || !httpEndpoint.Address.EndsWith(SEPARATOR + AAS + SEPARATOR))
                {
                    Endpoint = new Uri(httpEndpoint.Address + SEPARATOR + AAS);
                }
                else
                {
                    Endpoint = new Uri(httpEndpoint.Address);
                }
            }
        }
示例#24
0
        public SubmodelHttpClient(ISubmodelDescriptor submodelDescriptor) : this()
        {
            submodelDescriptor = submodelDescriptor ?? throw new ArgumentNullException(nameof(submodelDescriptor));
            HttpEndpoint httpEndpoint = submodelDescriptor.Endpoints?.OfType <HttpEndpoint>()?.FirstOrDefault();

            if (httpEndpoint == null || string.IsNullOrEmpty(httpEndpoint.Address))
            {
                throw new Exception("There is no http endpoint for instantiating a client");
            }
            else
            {
                if (!httpEndpoint.Address.EndsWith(SEPARATOR + SUBMODEL) || !httpEndpoint.Address.EndsWith(SEPARATOR + SUBMODEL + SEPARATOR))
                {
                    Endpoint = new Uri(httpEndpoint.Address + SEPARATOR + SUBMODEL);
                }
                else
                {
                    Endpoint = new Uri(httpEndpoint.Address);
                }
            }
        }
示例#25
0
        public async Task Consume(ConsumeContext <PublishMessage> context)
        {
            var contextMessage = context.Message;

            if (contextMessage.EndpointType != EndpointType.Http)
            {
                return;
            }

            var cancellationToken = context.CancellationToken;

            var endpoint = HttpEndpoint.FromPublishMessage(contextMessage);
            var method   = GetMethodByParameters(contextMessage.Parameters);
            var request  = new HttpRequestMessage(method, endpoint.Url)
            {
                Content = new StringContent(contextMessage.Message.Text)
            };
            var response = await _httpClient.SendAsync(request, cancellationToken);

            response.EnsureSuccessStatusCode();
        }
示例#26
0
 public GenericService(HttpClient client, HttpEndpoint endpoint) : base(client, endpoint)
 {
 }
示例#27
0
            public static string WriteEndpointImplementation(HttpController controller, HttpEndpoint endpoint)
            {
                return
                    ($@"

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(endpoint.ReturnType, false)} {endpoint.Name}
(
{string.Join($",{Environment.NewLine}", endpoint.GetParameters().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, false, false)}
}}

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(nameof(HttpResponseMessage), false)} {endpoint.Name}Raw
(
{string.Join($",{Environment.NewLine}", endpoint.GetParametersWithoutResponseTypes().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, false, true)}
}}

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(endpoint.ReturnType, true)} {endpoint.Name}Async
(
{string.Join($",{Environment.NewLine}", endpoint.GetParameters().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, true, false)}
}}

{SharedWriter.GetObsolete(endpoint)}
public {GetImplementationReturnType(nameof(HttpResponseMessage), true)} {endpoint.Name}RawAsync
(
{string.Join($",{Environment.NewLine}", endpoint.GetParametersWithoutResponseTypes().Select(SharedWriter.GetParameter))}
)
{{
{GetMethodDetails(controller, endpoint, true, true)}
}}

");
            }
示例#28
0
        private static HttpEndpoint ReadMethodAsHttpEndpoint(HttpController parent, MethodDeclarationSyntax syntax)
        {
            var attributes = syntax.DescendantNodes().OfType <AttributeListSyntax>().SelectMany(x => x.Attributes).ToList();

            var endpoint = new HttpEndpoint(parent);

            endpoint.Name = syntax.Identifier.ValueText.CleanMethodName();


            endpoint.Virtual  = syntax.Modifiers.Any(x => x.Text == "virtual");
            endpoint.Override = syntax.Modifiers.Any(x => x.Text == "override");
            endpoint.New      = syntax.Modifiers.Any(x => x.Text == "new");


            //Ignore generator attribute
            endpoint.Ignored = attributes.SingleOrDefault(x => x.Name.ToFullString().MatchesAttribute(nameof(NotGeneratedAttribute))) != null;


            //Route Attribute

            var routeAttribute = attributes.SingleOrDefault(x => x.Name.ToFullString().MatchesAttribute(nameof(RouteAttribute)));

            if (routeAttribute != null)            //Fetch route from RouteAttribute
            {
                endpoint.Route = new HttpRoute(routeAttribute.ArgumentList.Arguments.ToFullString().Replace("\"", "").Trim());
            }


            //HTTP Attribute
            var knownHttpAttributes = new List <string>
            {
                $"{Constants.Http}{HttpAttributeType.Delete}",
                $"{Constants.Http}{HttpAttributeType.Get}",
                $"{Constants.Http}{HttpAttributeType.Patch}",
                $"{Constants.Http}{HttpAttributeType.Post}",
                $"{Constants.Http}{HttpAttributeType.Put}",
            };

            var httpAttribute = attributes.SingleOrDefault(x => knownHttpAttributes.Any(y => x.Name.ToFullString().MatchesAttribute(y)));

            if (httpAttribute == null)
            {
                endpoint.Ignored = true;
            }
            else
            {
                var httpType = (HttpAttributeType)Enum.Parse(typeof(HttpAttributeType),
                                                             httpAttribute.Name
                                                             .ToFullString()
                                                             .Replace(Constants.Http, "")
                                                             .Replace(Constants.Attribute, ""));

                endpoint.HttpType = Helpers.HttpMethodFromEnum(httpType);
            }



            if (endpoint.Route == null && httpAttribute?.ArgumentList != null)            //If Route was never fetched from RouteAttribute or if they used the Http(template) override
            {
                endpoint.Route = new HttpRoute(httpAttribute.ArgumentList.Arguments.ToFullString().Replace("\"", "").Trim());
            }

            //Ignore method if it doesn't have a route or http attribute
            if (endpoint.Route == null && httpAttribute == null)
            {
                endpoint.Ignored = true;
                return(endpoint);
            }


            //Obsolete Attribute
            var obsoleteAttribute = attributes.SingleOrDefault(x => x.Name.ToFullString().MatchesAttribute(nameof(ObsoleteAttribute)));

            if (obsoleteAttribute != null)
            {
                endpoint.Obsolete        = true;
                endpoint.ObsoleteMessage = obsoleteAttribute.ArgumentList.Arguments.ToFullString().Replace("\"", "").Trim();
            }

            //Authorize Attribute
            endpoint.IsSecured = attributes.SingleOrDefault(x => x.Name.ToFullString().MatchesAttribute(nameof(AuthorizeAttribute))) != null;


            //Response types
            var responseTypes = attributes.Where(x => x.Name.ToFullString().MatchesAttribute(nameof(ProducesResponseTypeAttribute)));
            var responses     = responseTypes.Select(x => new ResponseTypeDefinition(x)).ToList();

            responses.Add(new ResponseTypeDefinition(true));

            endpoint.ResponseTypes = responses.Select(x => new ResponseType(x.Type, Helpers.EnumParse <HttpStatusCode>(x.StatusValue))).ToList();

            var duplicateResponseTypes = endpoint.GetResponseTypes().GroupBy(x => x.Status).Where(x => x.Count() > 1).ToList();

            if (duplicateResponseTypes.Any())
            {
                throw new NotSupportedException($"Endpoint has multiple response types of the same status defined. {string.Join(", ", duplicateResponseTypes.Select(x => x.Key?.ToString()))}");
            }
            //Add after so we don't get duplicate error from the null Status
            endpoint.ResponseTypes.Add(new ExceptionResponseType());



            var parameters = syntax.ParameterList.Parameters.Select(x => new ParameterDefinition(x, endpoint.GetFullRoute(parent))).ToList();


            var routeParams = parameters.Where(x => x.Options.FromRoute).Select(x => new RouteParameter(x.RouteName, x.Type, x.Default)).ToList();
            var queryParams = parameters.Where(x => x.Options.FromQuery).Select(x => new QueryParameter(x.Options.QueryName, x.Type, x.Default, x.Options.QueryObject)).ToList();
            var bodyParams  = parameters.Where(x => x.Options.FromBody).Select(x => new BodyParameter(x.Name, x.Type, x.Default)).SingleOrDefault();


            endpoint.Parameters = routeParams.Cast <IParameter>().Union(queryParams).Union(new List <IParameter> {
                bodyParams
            }).NotNull().ToList();

            endpoint.Parameters.Add(new CancellationTokenModifier());
            endpoint.Parameters.Add(new CookieModifier());
            endpoint.Parameters.Add(new HeadersModifier());
            endpoint.Parameters.Add(new TimeoutModifier());
            if (endpoint.IsSecured)
            {
                endpoint.Parameters.Add(new SecurityModifier());
            }


            var parameterHeaders = attributes.Where(x => x.Name.ToFullString().MatchesAttribute(nameof(HeaderParameterAttribute)))
                                   .Select(x => new ParameterHeaderDefinition(x))
                                   .ToList();

            endpoint.ParameterHeader = parameterHeaders.Select(x => new ParameterHeader(x.Name, x.Type, x.DefaultValue)).ToList();



            var headers = attributes.Where(x => x.Name.ToFullString().MatchesAttribute(nameof(IncludeHeaderAttribute)))
                          .Select(x => new HeaderDefinition(x))
                          .ToList();

            endpoint.ConstantHeader = headers.Select(x => new ConstantHeader(x.Name, x.Value)).ToList();


            var rawReturnType = syntax.ReturnType?.ToFullString();

            HashSet <string> returnContainerTypes = new HashSet <string>()
            {
                typeof(ValueTask).FullName,
                typeof(Task).FullName,
                typeof(ActionResult).FullName
            };


            var returnType = Helpers.GetTypeFromString(rawReturnType.Trim());

            while (returnContainerTypes.Any(x => Helpers.IsType(x, returnType?.Name)))
            {
                returnType = returnType.Arguments.SingleOrDefault();
            }

            if (Helpers.IsType(typeof(IActionResult).FullName, returnType?.Name))
            {
                returnType = null;
            }

            if (returnType?.Name == "void" ||
                (Helpers.IsType(typeof(Task).FullName, returnType?.Name) && (!returnType?.Arguments.Any() ?? false)))
            {
                returnType = null;
            }

            HashSet <string> fileResults = new HashSet <string>()
            {
                nameof(PhysicalFileResult),
                nameof(FileResult),
                nameof(FileContentResult),
                nameof(FileStreamResult),
                nameof(VirtualFileResult)
            };

            if (fileResults.Any(x => Helpers.IsType(x, returnType?.Name)))
            {
                returnType             = new Helpers.TypeString(typeof(Stream).FullName);
                endpoint.ReturnsStream = true;
            }

            rawReturnType = returnType?.ToString();

            endpoint.ReturnType = rawReturnType;



            var duplicateParameters = endpoint.GetParametersWithoutResponseTypes().GroupBy(x => x.Name).Where(x => x.Count() > 1).ToList();

            if (duplicateParameters.Any())
            {
                throw new NotSupportedException($"Endpoint has multiple parameters of the same name defined. {string.Join(", ", duplicateParameters.Select(x => x.Key?.ToString()))}");
            }



            return(endpoint);
        }
示例#29
0
 /// <summary>
 ///     Adds an endpoint for the server to listen on.</summary>
 /// <param name="key">
 ///     Unique key used to identify this endpoint.</param>
 /// <param name="endpoint">
 ///     The endpoint object.</param>
 public HttpServerOptions AddEndpoint(string key, HttpEndpoint endpoint)
 {
     _endpoints.Add(key, endpoint);
     return this;
 }
        /// <summary>
        /// Process a RESTful HTTP request
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="endpoint">HTTP endpoint descriptor</param>
        /// <param name="endpointConnection">Endpoint connection</param>
        /// <param name="sessionId">Session ID</param>
        /// <returns>Asynchronous task</returns>
        private async Task ProcessRestRequst(HttpContext context, HttpEndpoint endpoint, HttpEndpointConnection endpointConnection, int sessionId)
        {
            string body;

            if (endpoint.IsUploadRequest)
            {
                // Write to a temporary file
                string filename = Path.GetTempFileName();
                using (FileStream fileStream = new(filename, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    await context.Request.Body.CopyToAsync(fileStream);
                }

                // Adjust the file permissions if possible
                endpointConnection.GetPeerCredentials(out _, out int uid, out int gid);
                if (uid != 0 && gid != 0)
                {
                    LinuxApi.Commands.Chown(filename, uid, gid);
                }
                body = filename;
            }
            else
            {
                // Read the body content
                using StreamReader reader = new(context.Request.Body);
                body = await reader.ReadToEndAsync();
            }

            // Prepare the HTTP request notification
            ReceivedHttpRequest receivedHttpRequest = new()
            {
                Body        = body,
                ContentType = context.Request.ContentType,
                SessionId   = sessionId
            };

            foreach (var item in context.Request.Headers)
            {
                receivedHttpRequest.Headers.Add(item.Key, item.Value.ToString());
            }

            foreach (var item in context.Request.Query)
            {
                receivedHttpRequest.Queries.Add(item.Key, item.Value.ToString());
            }

            // Send it to the third-party application and get a response type
            await endpointConnection.SendHttpRequest(receivedHttpRequest);

            SendHttpResponse httpResponse = await endpointConnection.GetHttpResponse();

            // Send the response to the HTTP client
            context.Response.StatusCode = httpResponse.StatusCode;
            if (httpResponse.ResponseType == HttpResponseType.File)
            {
                context.Response.ContentType = "application/octet-stream";

                using FileStream fs = new(httpResponse.Response, FileMode.Open, FileAccess.Read);
                await fs.CopyToAsync(context.Response.Body);
            }
            else
            {
                switch (httpResponse.ResponseType)
                {
                case HttpResponseType.StatusCode:
                    context.Response.ContentType = null;
                    break;

                case HttpResponseType.PlainText:
                    context.Response.ContentType = "text/plain;charset=utf-8";
                    break;

                case HttpResponseType.JSON:
                    context.Response.ContentType = "application/json";
                    break;
                }

                await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(httpResponse.Response));
            }
        }
    }