コード例 #1
0
 /// <summary>
 /// Registers the actual middlware
 /// </summary>
 /// <param name="options">The options</param>
 /// <param name="routeBuilder">The routebuilder</param>
 protected internal void RegisterMiddleware(SPMiddlewareOptions options,
                                            IRouteBuilder routeBuilder)
 {
     this.options = options;
     foreach (var ent in entities)
     {
         Microsoft.AspNetCore.Http.RequestDelegate requestDelegate = context =>
         {
             var srv = (IGenericSPMiddleware)context.RequestServices.GetService(typeof(IGenericSPMiddleware));
             return(srv.HandleRequest(context, ent));
         };
         if (ent.Methods.ContainsKey("GET"))
         {
             routeBuilder.MapGet(GetUrlForMvcRouting(ent), requestDelegate);
         }
         if (ent.Methods.ContainsKey("PUT"))
         {
             routeBuilder.MapPut(GetUrlForMvcRouting(ent), requestDelegate);
         }
         if (ent.Methods.ContainsKey("POST"))
         {
             routeBuilder.MapPost(GetUrlForMvcRouting(ent), requestDelegate);
         }
         if (ent.Methods.ContainsKey("DELETE"))
         {
             routeBuilder.MapDelete(GetUrlForMvcRouting(ent), requestDelegate);
         }
     }
 }
コード例 #2
0
/// <summary>
        /// Registers the actual middlware
        /// </summary>
        /// <param name="options">The options</param>
        /// <param name="routeBuilder">The routebuilder</param>
        protected internal void RegisterMiddleware(SPMiddlewareOptions options,
                                                   IRouteBuilder routeBuilder)
        {
            this.options = options;
            foreach (var ent in entities)
            {
                Microsoft.AspNetCore.Http.RequestDelegate requestDelegate = context =>
                {
                    var srv = (IGenericSPMiddleware)context.RequestServices.GetService(typeof(IGenericSPMiddleware));
                    if (srv == null)
                    {
                        throw new InvalidOperationException("IGenericSPMiddleware not given");
                    }
                    return(srv.HandleRequest(context, ent));
                };
                foreach (var method in ent.Methods)
                {
                    switch (method.Key)
                    {
                    case OperationType.Get:
                        routeBuilder.MapGet(GetUrlForMvcRouting(ent), requestDelegate);
                        break;

                    case OperationType.Put:
                        routeBuilder.MapPut(GetUrlForMvcRouting(ent), requestDelegate);
                        break;

                    case OperationType.Post:
                        routeBuilder.MapPost(GetUrlForMvcRouting(ent), requestDelegate);
                        break;

                    case OperationType.Delete:
                        routeBuilder.MapDelete(GetUrlForMvcRouting(ent), requestDelegate);
                        break;

                    case OperationType.Patch:
                        // TODO: Testing

#if NETSTD2
                        routeBuilder.MapVerb("PATCH", GetUrlForMvcRouting(ent), requestDelegate);
#else
                        routeBuilder.Map(GetUrlForMvcRouting(ent), context =>
                        {
                            if (context.Request.Method.ToUpper() == "PATCH")
                            {
                                return(requestDelegate(context));
                            }
                            return(null);
                        });
#endif
                        break;

                    default:
                        throw new InvalidOperationException("Only Get, Pust, Post and Delete are allowed");
                    }
                }
            }
        }
コード例 #3
0
        public static IReadOnlyList <IEndpointConventionBuilder> MapOrchestrationEndpoints(
            this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder builder,
            PathString prefix)
        {
            var endpoints = new List <IEndpointConventionBuilder>();

            endpoints.Add(builder.MapGet(prefix + "/v1/orchestrations", async context =>
            {
                var extendedOrchestrationServiceClient = context.RequestServices.GetRequiredService <IExtendedOrchestrationServiceClient>();

                var query = context.ParseQuery <OrchestrationQuery>();

                var result = await extendedOrchestrationServiceClient.GetOrchestrationsAsync(query);

                await context.RespondJson(result);
            }).RequireAuthorization(DurableTaskPolicy.Read).WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsList"
            }));

            endpoints.Add(builder.MapPost(prefix + "/v1/orchestrations", async context =>
            {
                var taskHubClient = context.RequestServices.GetRequiredService <TaskHubClient>();
                var linkGenerator = context.RequestServices.GetRequiredService <LinkGenerator>();

                var request = await context.ParseBody <CreateOrchestrationRequest>();

                var validationResults = new List <ValidationResult>();
                if (!Validator.TryValidateObject(request, new ValidationContext(request), validationResults))
                {
                    await context.RespondJson(validationResults, 400);
                    return;
                }

                var instance = await taskHubClient.CreateOrchestrationInstanceAsync(
                    request.Name,
                    request.Version ?? string.Empty,
                    request.InstanceId,
                    request.Input,
                    request.Tags);

                var typedHeaders      = context.Response.GetTypedHeaders();
                typedHeaders.Location = new Uri(linkGenerator.GetUriByName("DurableTaskApi_OrchestrationsGet", new
                {
                    instanceId = instance.InstanceId
                }, context.Request.Scheme, context.Request.Host, context.Request.PathBase));

                await context.RespondJson(instance, 201);
            }).RequireAuthorization(DurableTaskPolicy.Create).WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsCreate"
            }));

            endpoints.Add(builder.MapGet(prefix + "/v1/orchestrations/{instanceId}", async context =>
            {
                var taskHubClient = context.RequestServices.GetRequiredService <TaskHubClient>();

                var instanceId = Uri.UnescapeDataString(context.Request.RouteValues["instanceId"].ToString());

                var state = await taskHubClient.GetOrchestrationStateAsync(instanceId);

                if (state == null)
                {
                    context.Response.StatusCode = 404;
                    return;
                }

                await context.RespondJson(state);
            }).RequireAuthorization(DurableTaskPolicy.Read)
                          .WithMetadata(new EndpointNameMetadata("DurableTaskApi_OrchestrationsGet"))
                          .WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsGet"
            }));

            endpoints.Add(builder.MapGet(prefix + "/v1/orchestrations/{instanceId}/{executionId}", async context =>
            {
                var taskHubClient = context.RequestServices.GetRequiredService <TaskHubClient>();

                var instanceId  = Uri.UnescapeDataString(context.Request.RouteValues["instanceId"].ToString());
                var executionId = Uri.UnescapeDataString(context.Request.RouteValues["executionId"].ToString());

                var state = await taskHubClient.GetOrchestrationStateAsync(instanceId, executionId);

                if (state == null)
                {
                    context.Response.StatusCode = 404;
                    return;
                }

                await context.RespondJson(state);
            }).RequireAuthorization(DurableTaskPolicy.Read)
                          .WithMetadata(new EndpointNameMetadata("DurableTaskApi_OrchestrationsGetExecution"))
                          .WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsGetExecution"
            }));

            endpoints.Add(builder.MapGet(prefix + "/v1/orchestrations/{instanceId}/{executionId}/history", async context =>
            {
                var taskHubClient = context.RequestServices.GetRequiredService <TaskHubClient>();

                var instanceId  = Uri.UnescapeDataString(context.Request.RouteValues["instanceId"].ToString());
                var executionId = Uri.UnescapeDataString(context.Request.RouteValues["executionId"].ToString());

                var orchestrationInstance = new OrchestrationInstance
                {
                    InstanceId  = instanceId,
                    ExecutionId = executionId
                };

                var history = await taskHubClient.GetOrchestrationHistoryAsync(orchestrationInstance);

                var events = new TypelessJsonDataConverter().Deserialize <HistoryEvent[]>(history);

                await context.RespondJson(events);
            }).RequireAuthorization(DurableTaskPolicy.ReadHistory).WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsGetExecutionHistory"
            }));

            endpoints.Add(builder.MapPost(prefix + "/v1/orchestrations/{instanceId}/terminate", async context =>
            {
                var taskHubClient = context.RequestServices.GetRequiredService <TaskHubClient>();

                var instanceId = Uri.UnescapeDataString(context.Request.RouteValues["instanceId"].ToString());

                var orchestrationInstance = new OrchestrationInstance
                {
                    InstanceId = instanceId
                };

                var request = await context.ParseBody <TerminateRequest>();

                await taskHubClient.TerminateInstanceAsync(orchestrationInstance, request.Reason);

                await context.RespondJson(new { });
            }).RequireAuthorization(DurableTaskPolicy.Terminate).WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsTerminate"
            }));

            endpoints.Add(builder.MapPost(prefix + "/v1/orchestrations/{instanceId}/rewind", async context =>
            {
                var extendedOrchestrationServiceClient = context.RequestServices.GetRequiredService <IExtendedOrchestrationServiceClient>();

                var instanceId = Uri.UnescapeDataString(context.Request.RouteValues["instanceId"].ToString());

                var request = await context.ParseBody <RewindRequest>();

                await extendedOrchestrationServiceClient.RewindTaskOrchestrationAsync(instanceId, request.Reason);

                await context.RespondJson(new { });
            }).RequireAuthorization(DurableTaskPolicy.Rewind).WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsRewind"
            }));

            endpoints.Add(builder.MapPost(prefix + "/v1/orchestrations/{instanceId}/raiseevent/{eventName}", async context =>
            {
                var taskHubClient = context.RequestServices.GetRequiredService <TaskHubClient>();

                var instanceId = Uri.UnescapeDataString(context.Request.RouteValues["instanceId"].ToString());
                var eventName  = Uri.UnescapeDataString(context.Request.RouteValues["eventName"].ToString());

                var orchestrationInstance = new OrchestrationInstance
                {
                    InstanceId = instanceId
                };

                var eventData = await context.ParseBody <JToken>();

                await taskHubClient.RaiseEventAsync(orchestrationInstance, eventName, eventData);

                await context.RespondJson(new { });
            }).RequireAuthorization(DurableTaskPolicy.RaiseEvent).WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsRaiseEvent"
            }));

            endpoints.Add(builder.MapDelete(prefix + "/v1/orchestrations/{instanceId}", async context =>
            {
                var extendedOrchestrationServiceClient = context.RequestServices.GetRequiredService <IExtendedOrchestrationServiceClient>();

                var instanceId = Uri.UnescapeDataString(context.Request.RouteValues["instanceId"].ToString());

                var result = await extendedOrchestrationServiceClient.PurgeInstanceHistoryAsync(instanceId);

                await context.RespondJson(new { });
            }).RequireAuthorization(DurableTaskPolicy.Purge).WithMetadata(new DurableTaskEndpointMetadata
            {
                Id = "OrchestrationsPurgeInstance"
            }));

            return(endpoints);
        }
コード例 #4
0
 public static void MapAPIEndpoints(Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints)
 {
     endpoints.MapGet("/api/recipe/all/", async(context) =>
     {
         if (!context.Request.Query.ContainsKey("page") ||
             !int.TryParse(context.Request.Query["page"].ToString(), out int page))
         {
             page = 0;
         }
         if (!context.Request.Query.ContainsKey("count") ||
             !int.TryParse(context.Request.Query["count"].ToString(), out int count))
         {
             count = 100;
         }
         RecipeAPI api = new RecipeAPI();
         await context.Response.WriteAsJsonAsync(api.GetAll(new AuthenticationToken(), page, count));
     });
     endpoints.MapGet("/api/recipe/", async(context) =>
     {
         if (!context.Request.Query.ContainsKey("id") ||
             !long.TryParse(context.Request.Query["id"].ToString(), out long id))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 404, Message = "Could not find a Recipe with that ID." });
         }
         else
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.GetOne(new AuthenticationToken(), id));
         }
     });
     endpoints.MapGet("/api/recipe/mine/", async(context) => {
         long id = 0;
         if ((!context.Request.Query.ContainsKey("name") && !context.Request.Query.ContainsKey("id")) ||
             (context.Request.Query.ContainsKey("name") && string.IsNullOrWhiteSpace(context.Request.Query["name"].ToString()) ||
              (context.Request.Query.ContainsKey("id") && !long.TryParse(context.Request.Query["id"].ToString(), out id))))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Either both no name and no id specified for that Cook, or one of the two wasn't readable." });
         }
         else
         {
             int page = 0, count = 100;
             if (context.Request.Query.ContainsKey("page") && !int.TryParse(context.Request.Query["page"].ToString(), out page) ||
                 (context.Request.Query.ContainsKey("count") && !int.TryParse(context.Request.Query["count"].ToString(), out count)) ||
                 (context.Request.Query.ContainsKey("page") && !context.Request.Query.ContainsKey("count")))
             {
                 await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Either couldn't read page or count requested, or page was requested and count (per page) wasn't." });
             }
             else
             {
                 AuthenticationToken tokenUser = new AuthenticationToken {
                     ApplicationWideId = id, ApplicationWideName = (context.Request.Query.ContainsKey("name")) ? context.Request.Query["name"].ToString() : ""
                 };
                 RecipeAPI api = new RecipeAPI();
                 await context.Response.WriteAsJsonAsync(api.GetMine(tokenUser, page, count));
             }
         }
     });
     endpoints.MapDelete("/api/recipe", async(context) =>
     {
         if (!context.Request.Query.ContainsKey("id") ||
             !long.TryParse(context.Request.Query["id"].ToString(), out long id))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 404, Message = "Could not find a Recipe with that ID." });
         }
         else
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.Delete(new AuthenticationToken(), id));
         }
     });
     endpoints.MapPost("/api/recipe", async(context) =>
     {
         Stream body   = context.Request.Body;
         Recipe recipe = null;
         if (body != null)
         {
             string bodyJsonString = await(new StreamReader(body)).ReadToEndAsync();
             recipe = JsonSerializer.Deserialize <Recipe>(bodyJsonString);
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Body of request must contain a Recipe in Json format." });
         }
         if (recipe != null)
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.Create(new AuthenticationToken(), recipe));
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Could not read a Recipe from the body of your request." });
         }
     });
     endpoints.MapPut("/api/recipe", async(context) => {
         Stream body   = context.Request.Body;
         Recipe recipe = null;
         if (body != null)
         {
             string bodyJsonString = await(new StreamReader(body)).ReadToEndAsync();
             recipe = JsonSerializer.Deserialize <Recipe>(bodyJsonString);
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Body of request must contain a Recipe in Json format." });
         }
         if (recipe != null)
         {
             RecipeAPI api = new RecipeAPI();
             await context.Response.WriteAsJsonAsync(api.Update(new AuthenticationToken(), recipe));
         }
         else
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 400, Message = "Could not read a Recipe from the body of your request." });
         }
     });
 }
コード例 #5
0
 public static void MapAPIEndpoints(Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints)
 {
     endpoints.MapGet("/", async context =>
     {
         await context.Response.WriteAsync("Hello World!");
     });
     endpoints.MapGet("/api/cook/all/", async(context) =>
     {
         if (!context.Request.Query.ContainsKey("page") ||
             !int.TryParse(context.Request.Query["page"].ToString(), out int page))
         {
             page = 0;
         }
         if (!context.Request.Query.ContainsKey("count") ||
             !int.TryParse(context.Request.Query["count"].ToString(), out int count))
         {
             count = 100;
         }
         CookAPI api         = new CookAPI();
         Models.Cook[] cooks = await api.GetAll(new AuthenticationToken(), page, count);
         await context.Response.WriteAsJsonAsync(api.GetAll(new AuthenticationToken(), page, count));
     });
     endpoints.MapGet("/api/cook/", async context =>
     {
         if (!context.Request.Query.ContainsKey("id") ||
             !long.TryParse(context.Request.Query["id"].ToString(), out long id))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 404, Message = "Could not find a Cook with that ID." });
         }
         else
         {
             CookAPI api = new CookAPI();
             await context.Response.WriteAsJsonAsync(api.GetOne(new AuthenticationToken(), id));
         }
     });
     endpoints.MapDelete("/api/cook", async context =>
     {
         if (!context.Request.Query.ContainsKey("id") ||
             !long.TryParse(context.Request.Query["id"].ToString(), out long id))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 404, Message = "Could not find a Cook with that ID." });
         }
         else
         {
             CookAPI api = new CookAPI();
             await context.Response.WriteAsJsonAsync(api.Delete(new AuthenticationToken(), id));
         }
     });
     endpoints.MapPost("/api/cook", async context =>
     {
         if (!context.Request.Query.ContainsKey("name") ||
             string.IsNullOrWhiteSpace(context.Request.Query["name"].ToString()))
         {
             await context.Response.WriteAsJsonAsync(new { ResponseCode = 404, Message = "Could not create a Cook with no name." });
         }
         else
         {
             var name    = context.Request.Query["name"].ToString();
             CookAPI api = new CookAPI();
             await context.Response.WriteAsJsonAsync(api.Create(new AuthenticationToken(), name));
         }
     });
 }