Browse Source

language filter

zinab_elgendy 8 months ago
parent
commit
8cf0ff4603

+ 12 - 0
MTWorkHR.API/.config/dotnet-tools.json

@@ -0,0 +1,12 @@
+{
+  "version": 1,
+  "isRoot": true,
+  "tools": {
+    "dotnet-ef": {
+      "version": "8.0.4",
+      "commands": [
+        "dotnet-ef"
+      ]
+    }
+  }
+}

+ 53 - 2
MTWorkHR.API/Program.cs

@@ -9,6 +9,9 @@ using MTWorkHR.Application.Filters;
 using MTWorkHR.Application.StartupService;
 using Microsoft.AspNetCore.Mvc;
 using MTWorkHR.Infrastructure.DBContext;
+using Microsoft.AspNetCore.Mvc.Controllers;
+using Microsoft.OpenApi.Models;
+using MTWorkHR.API.Swagger;
 
 var builder = WebApplication.CreateBuilder(args);
 
@@ -40,15 +43,63 @@ builder.Services.Configure<ApiBehaviorOptions>(options =>
 });
 // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 builder.Services.AddEndpointsApiExplorer();
-builder.Services.AddSwaggerGen();
+//builder.Services.AddSwaggerGen();
+//--------------------------
+builder.Services.AddSwaggerGen(swagger =>
+{
+    //This is to apply global headers for all requests
+    swagger.OperationFilter<HeaderOperationFilter>();
+
+    //This is to export enums to front
+    swagger.SchemaFilter<EnumSchemaFilter>();
+
+    //This is to generate the Default UI of Swagger Documentation  
+    swagger.SwaggerDoc("v1", new OpenApiInfo
+    {
+        Version = "v1",
+        Title = "MTWorkHR.API",
+        Description = "MTWorkHR.API"
+    });
 
+    swagger.CustomOperationIds(
+            d => (d.ActionDescriptor as ControllerActionDescriptor)?.ControllerName + (d.ActionDescriptor as ControllerActionDescriptor)?.ActionName
+        );
+
+    // To Enable authorization using Swagger (JWT)  
+    swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
+    {
+        Name = "Authorization",
+        Type = SecuritySchemeType.ApiKey,
+        Scheme = "Bearer",
+        BearerFormat = "JWT",
+        In = ParameterLocation.Header,
+        Description = "Enter 'Bearer' [space] and then your valid token in the text input below.\r\n\r\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\"",
+    });
+    swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
+                {
+                    {
+                          new OpenApiSecurityScheme
+                            {
+                                Reference = new OpenApiReference
+                                {
+                                    Type = ReferenceType.SecurityScheme,
+                                    Id = "Bearer"
+                                }
+                            },
+                            new string[] {}
+
+                    }
+                });
+});
+//--------------------------
 var app = builder.Build();
 
 // Configure the HTTP request pipeline.
 // if (app.Environment.IsDevelopment())
 // {
 app.UseSwagger();
-app.UseSwaggerUI();
+//app.UseSwaggerUI();
+app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MTWorkHR.API v1"));
 // }
 
 

+ 30 - 0
MTWorkHR.API/Swagger/EnumSchemaFilter.cs

@@ -0,0 +1,30 @@
+using Microsoft.OpenApi.Any;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+using System;
+using System.Linq;
+
+namespace MTWorkHR.API.Swagger
+{
+    public class EnumSchemaFilter : ISchemaFilter
+    {
+        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
+        {
+            var type = context.Type;
+            if (type.IsEnum)
+            {
+                // Add enum type information once
+                if (schema.Extensions.ContainsKey("x-enumNames")) return;
+
+                var valuesArr = new OpenApiArray();
+                valuesArr.AddRange(Enum.GetNames(context.Type)
+                                                .Select(value => new OpenApiString(value)));
+
+                schema.Extensions.Add(
+                    "x-enumNames",
+                    valuesArr
+                );
+            }
+        }
+    }
+}

+ 117 - 0
MTWorkHR.API/Swagger/HeaderOperationFilter.cs

@@ -0,0 +1,117 @@
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace MTWorkHR.API.Swagger
+{
+    public class HeaderOperationFilter : IOperationFilter
+    {
+        public void Apply(OpenApiOperation operation, OperationFilterContext context)
+        {
+            operation.Parameters ??= new List<OpenApiParameter>();
+
+            //if (context.MethodInfo.GetCustomAttribute(typeof(SwaggerHeaderAttribute)) is SwaggerHeaderAttribute attribute)
+            //{
+            var parameters = new string[] { "lang" };
+
+            var existingParams = operation.Parameters.Where(p =>
+                p.In == ParameterLocation.Header && parameters.Contains(p.Name)).ToList();
+
+            foreach (var param in existingParams)// remove description from [FromHeader] argument attribute
+            {
+                operation.Parameters.Remove(param);
+            }
+
+            //operation.Parameters.Add(new OpenApiParameter
+            //{
+            //    Name = "branch",
+            //    In = ParameterLocation.Header,
+            //    Description = "current acive branch",
+            //    Required = false,
+
+            //    // this schema commented because it is working in swagger but not working in openapi-generator-cli, we use the Content instead below
+            //    //Schema = string.IsNullOrEmpty("")
+            //    //    ? null
+            //    //    : new OpenApiSchema
+            //    //    {
+            //    //        Type = "String",
+            //    //        Default = new OpenApiString("")
+            //    //    },
+            //    Content = new Dictionary<string, OpenApiMediaType>
+            //            {
+            //                {
+            //                    "text/plain", new OpenApiMediaType
+            //                    {
+            //                        Schema = new OpenApiSchema
+            //                        {
+            //                            Type = "string",
+            //                            Required = new HashSet<string>{ "string" },
+            //                            Properties = new Dictionary<string, OpenApiSchema>
+            //                            {
+            //                                {
+            //                                    "string", new OpenApiSchema()
+            //                                    {
+            //                                        Type = "string",
+            //                                        Format = "text"
+            //                                    }
+            //                                }
+            //                            }
+            //                        }
+            //                    }
+            //                }
+            //            }
+            //});
+
+            operation.Parameters.Add(new OpenApiParameter
+            {
+                Name = "lang",
+                In = ParameterLocation.Header,
+                Description = "current acive lang",
+                Required = false,
+                Content = new Dictionary<string, OpenApiMediaType>
+                        {
+                            {
+                                "text/plain", new OpenApiMediaType
+                                {
+                                    Schema = new OpenApiSchema
+                                    {
+                                        Type = "string",
+                                        Required = new HashSet<string>{ "string" },
+                                        Properties = new Dictionary<string, OpenApiSchema>
+                                        {
+                                            {
+                                                "string", new OpenApiSchema()
+                                                {
+                                                    Type = "string",
+                                                    Format = "text"
+                                                }
+                                            }
+                                        }
+                                    }
+                                }
+                            }
+                        }
+            });
+
+            //}
+        }
+    }
+
+    public class SwaggerHeaderAttribute : Attribute
+    {
+        public string HeaderName { get; }
+        public string Description { get; }
+        public string DefaultValue { get; }
+        public bool IsRequired { get; }
+
+        public SwaggerHeaderAttribute(string headerName, string description = null, string defaultValue = null, bool isRequired = false)
+        {
+            HeaderName = headerName;
+            Description = description;
+            DefaultValue = defaultValue;
+            IsRequired = isRequired;
+        }
+    }
+}