├── .gitignore ├── AspNetCore.ResponseWrapper.sln ├── LICENSE ├── README.md ├── logo.png ├── samples ├── CustomResponseWrapper │ ├── Controllers │ │ └── WeatherForecastController.cs │ ├── CustomResponseWrapper.csproj │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── ResponseWrapper │ │ ├── CustomResponseWrapper.cs │ │ └── CustomResponseWrapper`.cs │ ├── WeatherForecast.cs │ ├── appsettings.Development.json │ └── appsettings.json └── DefaultWrapperSample │ ├── Controllers │ └── WeatherForecastController.cs │ ├── DefaultWrapperSample.csproj │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── WeatherForecast.cs │ ├── appsettings.Development.json │ └── appsettings.json └── src └── AspNetCore.ResponseWrapper ├── Abstractions ├── DisableWrapperAttribute.cs ├── IDisableWrapperMetadata.cs ├── IResponseWrapper.cs └── IResponseWrapper`.cs ├── AspNetCore.ResponseWrapper.csproj ├── Mvc ├── Abstractions │ └── IResultWrapperFilter.cs └── Filters │ ├── ModelInvalidWrapperFilter.cs │ └── ResultWrapperFilter.cs ├── ResponseWrapper.cs ├── ResponseWrapperApplicationModelProvider.cs ├── ResponseWrapperBuilderExtensions.cs ├── ResponseWrapperDefaults.cs ├── ResponseWrapperOptions.cs └── ResponseWrapper`.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | .idea/ 13 | 14 | # User-specific files (MonoDevelop/Xamarin Studio) 15 | *.userprefs 16 | 17 | # Mono auto generated files 18 | mono_crash.* 19 | 20 | # Build results 21 | [Dd]ebug/ 22 | [Dd]ebugPublic/ 23 | [Rr]elease/ 24 | [Rr]eleases/ 25 | x64/ 26 | x86/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # StyleCop 66 | StyleCopReport.xml 67 | 68 | # Files built by Visual Studio 69 | *_i.c 70 | *_p.c 71 | *_h.h 72 | *.ilk 73 | *.meta 74 | *.obj 75 | *.iobj 76 | *.pch 77 | *.pdb 78 | *.ipdb 79 | *.pgc 80 | *.pgd 81 | *.rsp 82 | *.sbr 83 | *.tlb 84 | *.tli 85 | *.tlh 86 | *.tmp 87 | *.tmp_proj 88 | *_wpftmp.csproj 89 | *.log 90 | *.vspscc 91 | *.vssscc 92 | .builds 93 | *.pidb 94 | *.svclog 95 | *.scc 96 | 97 | # Chutzpah Test files 98 | _Chutzpah* 99 | 100 | # Visual C++ cache files 101 | ipch/ 102 | *.aps 103 | *.ncb 104 | *.opendb 105 | *.opensdf 106 | *.sdf 107 | *.cachefile 108 | *.VC.db 109 | *.VC.VC.opendb 110 | 111 | # Visual Studio profiler 112 | *.psess 113 | *.vsp 114 | *.vspx 115 | *.sap 116 | 117 | # Visual Studio Trace Files 118 | *.e2e 119 | 120 | # TFS 2012 Local Workspace 121 | $tf/ 122 | 123 | # Guidance Automation Toolkit 124 | *.gpState 125 | 126 | # ReSharper is a .NET coding add-in 127 | _ReSharper*/ 128 | *.[Rr]e[Ss]harper 129 | *.DotSettings.user 130 | 131 | # TeamCity is a build add-in 132 | _TeamCity* 133 | 134 | # DotCover is a Code Coverage Tool 135 | *.dotCover 136 | 137 | # AxoCover is a Code Coverage Tool 138 | .axoCover/* 139 | !.axoCover/settings.json 140 | 141 | # Visual Studio code coverage results 142 | *.coverage 143 | *.coveragexml 144 | 145 | # NCrunch 146 | _NCrunch_* 147 | .*crunch*.local.xml 148 | nCrunchTemp_* 149 | 150 | # MightyMoose 151 | *.mm.* 152 | AutoTest.Net/ 153 | 154 | # Web workbench (sass) 155 | .sass-cache/ 156 | 157 | # Installshield output folder 158 | [Ee]xpress/ 159 | 160 | # DocProject is a documentation generator add-in 161 | DocProject/buildhelp/ 162 | DocProject/Help/*.HxT 163 | DocProject/Help/*.HxC 164 | DocProject/Help/*.hhc 165 | DocProject/Help/*.hhk 166 | DocProject/Help/*.hhp 167 | DocProject/Help/Html2 168 | DocProject/Help/html 169 | 170 | # Click-Once directory 171 | publish/ 172 | 173 | # Publish Web Output 174 | *.[Pp]ublish.xml 175 | *.azurePubxml 176 | # Note: Comment the next line if you want to checkin your web deploy settings, 177 | # but database connection strings (with potential passwords) will be unencrypted 178 | *.pubxml 179 | *.publishproj 180 | 181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 182 | # checkin your Azure Web App publish settings, but sensitive information contained 183 | # in these scripts will be unencrypted 184 | PublishScripts/ 185 | 186 | # NuGet Packages 187 | *.nupkg 188 | # NuGet Symbol Packages 189 | *.snupkg 190 | # The packages folder can be ignored because of Package Restore 191 | **/[Pp]ackages/* 192 | # except build/, which is used as an MSBuild target. 193 | !**/[Pp]ackages/build/ 194 | # Uncomment if necessary however generally it will be regenerated when needed 195 | #!**/[Pp]ackages/repositories.config 196 | # NuGet v3's project.json files produces more ignorable files 197 | *.nuget.props 198 | *.nuget.targets 199 | 200 | # Microsoft Azure Build Output 201 | csx/ 202 | *.build.csdef 203 | 204 | # Microsoft Azure Emulator 205 | ecf/ 206 | rcf/ 207 | 208 | # Windows Store app package directories and files 209 | AppPackages/ 210 | BundleArtifacts/ 211 | Package.StoreAssociation.xml 212 | _pkginfo.txt 213 | *.appx 214 | *.appxbundle 215 | *.appxupload 216 | 217 | # Visual Studio cache files 218 | # files ending in .cache can be ignored 219 | *.[Cc]ache 220 | # but keep track of directories ending in .cache 221 | !?*.[Cc]ache/ 222 | 223 | # Others 224 | ClientBin/ 225 | ~$* 226 | *~ 227 | *.dbmdl 228 | *.dbproj.schemaview 229 | *.jfm 230 | *.pfx 231 | *.publishsettings 232 | orleans.codegen.cs 233 | 234 | # Including strong name files can present a security risk 235 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 236 | #*.snk 237 | 238 | # Since there are multiple workflows, uncomment next line to ignore bower_components 239 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 240 | #bower_components/ 241 | 242 | # RIA/Silverlight projects 243 | Generated_Code/ 244 | 245 | # Backup & report files from converting an old project file 246 | # to a newer Visual Studio version. Backup files are not needed, 247 | # because we have git ;-) 248 | _UpgradeReport_Files/ 249 | Backup*/ 250 | UpgradeLog*.XML 251 | UpgradeLog*.htm 252 | ServiceFabricBackup/ 253 | *.rptproj.bak 254 | 255 | # SQL Server files 256 | *.mdf 257 | *.ldf 258 | *.ndf 259 | 260 | # Business Intelligence projects 261 | *.rdl.data 262 | *.bim.layout 263 | *.bim_*.settings 264 | *.rptproj.rsuser 265 | *- [Bb]ackup.rdl 266 | *- [Bb]ackup ([0-9]).rdl 267 | *- [Bb]ackup ([0-9][0-9]).rdl 268 | 269 | # Microsoft Fakes 270 | FakesAssemblies/ 271 | 272 | # GhostDoc plugin setting file 273 | *.GhostDoc.xml 274 | 275 | # Node.js Tools for Visual Studio 276 | .ntvs_analysis.dat 277 | node_modules/ 278 | 279 | # Visual Studio 6 build log 280 | *.plg 281 | 282 | # Visual Studio 6 workspace options file 283 | *.opt 284 | 285 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 286 | *.vbw 287 | 288 | # Visual Studio LightSwitch build output 289 | **/*.HTMLClient/GeneratedArtifacts 290 | **/*.DesktopClient/GeneratedArtifacts 291 | **/*.DesktopClient/ModelManifest.xml 292 | **/*.Server/GeneratedArtifacts 293 | **/*.Server/ModelManifest.xml 294 | _Pvt_Extensions 295 | 296 | # Paket dependency manager 297 | .paket/paket.exe 298 | paket-files/ 299 | 300 | # FAKE - F# Make 301 | .fake/ 302 | 303 | # CodeRush personal settings 304 | .cr/personal 305 | 306 | # Python Tools for Visual Studio (PTVS) 307 | __pycache__/ 308 | *.pyc 309 | 310 | # Cake - Uncomment if you are using it 311 | # tools/** 312 | # !tools/packages.config 313 | 314 | # Tabs Studio 315 | *.tss 316 | 317 | # Telerik's JustMock configuration file 318 | *.jmconfig 319 | 320 | # BizTalk build output 321 | *.btp.cs 322 | *.btm.cs 323 | *.odx.cs 324 | *.xsd.cs 325 | 326 | # OpenCover UI analysis results 327 | OpenCover/ 328 | 329 | # Azure Stream Analytics local run output 330 | ASALocalRun/ 331 | 332 | # MSBuild Binary and Structured Log 333 | *.binlog 334 | 335 | # NVidia Nsight GPU debugger configuration file 336 | *.nvuser 337 | 338 | # MFractors (Xamarin productivity tool) working folder 339 | .mfractor/ 340 | 341 | # Local History for Visual Studio 342 | .localhistory/ 343 | 344 | # BeatPulse healthcheck temp database 345 | healthchecksdb 346 | 347 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 348 | MigrationBackup/ 349 | 350 | # Ionide (cross platform F# VS Code tools) working folder 351 | .ionide/ 352 | -------------------------------------------------------------------------------- /AspNetCore.ResponseWrapper.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{75F16707-DB7C-4C43-8578-219A365261D6}" 4 | EndProject 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspNetCore.ResponseWrapper", "src\AspNetCore.ResponseWrapper\AspNetCore.ResponseWrapper.csproj", "{F841A793-72D0-41D0-83BE-6186E66233E0}" 6 | EndProject 7 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{06C1EE9B-110F-45A4-B2E5-96997D00D574}" 8 | EndProject 9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DefaultWrapperSample", "samples\DefaultWrapperSample\DefaultWrapperSample.csproj", "{77007EDC-0F47-42BB-AA45-6CDA6CF15867}" 10 | EndProject 11 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomResponseWrapper", "samples\CustomResponseWrapper\CustomResponseWrapper.csproj", "{90B9B0B7-7F6E-49C2-B89A-EB898369A18F}" 12 | EndProject 13 | Global 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Release|Any CPU = Release|Any CPU 17 | EndGlobalSection 18 | GlobalSection(NestedProjects) = preSolution 19 | {F841A793-72D0-41D0-83BE-6186E66233E0} = {75F16707-DB7C-4C43-8578-219A365261D6} 20 | {77007EDC-0F47-42BB-AA45-6CDA6CF15867} = {06C1EE9B-110F-45A4-B2E5-96997D00D574} 21 | {90B9B0B7-7F6E-49C2-B89A-EB898369A18F} = {06C1EE9B-110F-45A4-B2E5-96997D00D574} 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {F841A793-72D0-41D0-83BE-6186E66233E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {F841A793-72D0-41D0-83BE-6186E66233E0}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {F841A793-72D0-41D0-83BE-6186E66233E0}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {F841A793-72D0-41D0-83BE-6186E66233E0}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {77007EDC-0F47-42BB-AA45-6CDA6CF15867}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {77007EDC-0F47-42BB-AA45-6CDA6CF15867}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {77007EDC-0F47-42BB-AA45-6CDA6CF15867}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {77007EDC-0F47-42BB-AA45-6CDA6CF15867}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {90B9B0B7-7F6E-49C2-B89A-EB898369A18F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {90B9B0B7-7F6E-49C2-B89A-EB898369A18F}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {90B9B0B7-7F6E-49C2-B89A-EB898369A18F}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {90B9B0B7-7F6E-49C2-B89A-EB898369A18F}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 huiyuanai709 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AspNetCore.ResponseWrapper 2 | AspNetCore.ResponseWrapper is a HTTP API response wrapper, It supports various Action return type, Model invalid wrapper, Swagger response display and also supports custom response wrapper. 3 | 4 | ## Features: 5 | 6 | 1. ModelInvalid response wrapper 7 | 2. ObjectResult/EmptyResult response wrapper 8 | 3. Swagger response wrapped type display 9 | 4. Custom response wrapper 10 | 5. Disable response wrapper for specified Controller/Action 11 | 12 | ## Usage 13 | 14 | 1. Basic 15 | ```c# 16 | builder.Services.AddControllers().AddResponseWrapper(); 17 | ``` 18 | 2. Disable response wrapper 19 | ```C# 20 | [DisableWrapper] 21 | [ApiController] 22 | [Route("[controller]")] 23 | public class WeatherForecastController : ControllerBase 24 | { 25 | } 26 | ``` 27 | 28 | or 29 | ```C# 30 | [DisableWrapper] 31 | [HttpGet("GetWeatherForecast")] 32 | public IEnumerable Get() 33 | { 34 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 35 | { 36 | Date = DateTime.Now.AddDays(index), 37 | TemperatureC = Random.Shared.Next(-20, 55), 38 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 39 | }) 40 | .ToArray(); 41 | } 42 | ``` 43 | 44 | See samples... 45 | 46 | ## Installation 47 | ```shell 48 | dotnet add Package AspNetCore.ResponseWrapper 49 | ``` -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huiyuanai709/AspNetCore.ResponseWrapper/aa1c7bca06168e18c4c4c7ef56550622fa3cc0cc/logo.png -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace CustomResponseWrapper.Controllers; 4 | 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | 16 | public WeatherForecastController(ILogger logger) 17 | { 18 | _logger = logger; 19 | } 20 | 21 | [HttpGet(Name = "GetWeatherForecast")] 22 | public IEnumerable Get() 23 | { 24 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 25 | { 26 | Date = DateTime.Now.AddDays(index), 27 | TemperatureC = Random.Shared.Next(-20, 55), 28 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 29 | }) 30 | .ToArray(); 31 | } 32 | } -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/CustomResponseWrapper.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/Program.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper; 2 | using CustomResponseWrapper.ResponseWrapper; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | 8 | builder.Services.AddControllers().AddResponseWrapper(options => 9 | { 10 | options.ResponseWrapper = new CustomResponseWrapper.ResponseWrapper.CustomResponseWrapper(); 11 | options.GenericResponseWrapper = new CustomResponseWrapper(); 12 | }); 13 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 14 | builder.Services.AddEndpointsApiExplorer(); 15 | builder.Services.AddSwaggerGen(); 16 | 17 | var app = builder.Build(); 18 | 19 | // Configure the HTTP request pipeline. 20 | if (app.Environment.IsDevelopment()) 21 | { 22 | app.UseSwagger(); 23 | app.UseSwaggerUI(); 24 | } 25 | 26 | app.UseHttpsRedirection(); 27 | 28 | app.UseAuthorization(); 29 | 30 | app.MapControllers(); 31 | 32 | app.Run(); -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:32381", 8 | "sslPort": 44348 9 | } 10 | }, 11 | "profiles": { 12 | "CustomResponseWrapper": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7145;http://localhost:5145", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/ResponseWrapper/CustomResponseWrapper.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper.Abstractions; 2 | 3 | namespace CustomResponseWrapper.ResponseWrapper; 4 | 5 | public class CustomResponseWrapper : IResponseWrapper 6 | { 7 | public bool Success => Code == 0; 8 | 9 | public int Code { get; set; } 10 | 11 | public string? Message { get; set; } 12 | 13 | public CustomResponseWrapper() 14 | { 15 | } 16 | 17 | public CustomResponseWrapper(int code, string? message) 18 | { 19 | Code = code; 20 | Message = message; 21 | } 22 | 23 | public IResponseWrapper Ok() 24 | { 25 | return new CustomResponseWrapper(0, null); 26 | } 27 | 28 | public IResponseWrapper BusinessError(string message) 29 | { 30 | return new CustomResponseWrapper(1, message); 31 | } 32 | 33 | public IResponseWrapper ClientError(string message) 34 | { 35 | return new CustomResponseWrapper(400, message); 36 | } 37 | } -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/ResponseWrapper/CustomResponseWrapper`.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper.Abstractions; 2 | 3 | namespace CustomResponseWrapper.ResponseWrapper; 4 | 5 | public class CustomResponseWrapper : CustomResponseWrapper, IResponseWrapper 6 | { 7 | public TResponse? Result { get; set; } 8 | 9 | public CustomResponseWrapper() 10 | { 11 | } 12 | 13 | public CustomResponseWrapper(int code, string? message, TResponse? result) : base(code, message) 14 | { 15 | Result = result; 16 | } 17 | 18 | public IResponseWrapper Ok(TResponse response) 19 | { 20 | return new CustomResponseWrapper(0, null, response); 21 | } 22 | } -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace CustomResponseWrapper; 2 | 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /samples/CustomResponseWrapper/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /samples/DefaultWrapperSample/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace DefaultWrapperSample.Controllers; 4 | 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | 16 | public WeatherForecastController(ILogger logger) 17 | { 18 | _logger = logger; 19 | } 20 | 21 | [HttpGet("GetWeatherForecast")] 22 | public IEnumerable Get() 23 | { 24 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 25 | { 26 | Date = DateTime.Now.AddDays(index), 27 | TemperatureC = Random.Shared.Next(-20, 55), 28 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 29 | }) 30 | .ToArray(); 31 | } 32 | 33 | [HttpGet("GetWeatherForecastAsync")] 34 | public async Task> GetAsync() 35 | { 36 | await Task.CompletedTask; 37 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 38 | { 39 | Date = DateTime.Now.AddDays(index), 40 | TemperatureC = Random.Shared.Next(-20, 55), 41 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 42 | }) 43 | .ToArray(); 44 | } 45 | 46 | [HttpGet("ActionResultAsync")] 47 | public async Task>> GetActionResult() 48 | { 49 | await Task.CompletedTask; 50 | return Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast 51 | { 52 | Date = DateTime.Now.AddDays(index), 53 | TemperatureC = Random.Shared.Next(-20, 55), 54 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 55 | }) 56 | .ToArray()); 57 | } 58 | 59 | [HttpGet("GetTemperature")] 60 | public int GetTemperatureC() 61 | { 62 | return Random.Shared.Next(-20, 55); 63 | } 64 | 65 | [HttpGet("GetTemperatureAsync")] 66 | public async Task GetTemperatureCAsync() 67 | { 68 | await Task.CompletedTask; 69 | return Random.Shared.Next(-20, 55); 70 | } 71 | 72 | [HttpGet("Suitable")] 73 | public bool Suitable() 74 | { 75 | return Random.Shared.Next(-20, 55) >= 20; 76 | } 77 | 78 | [HttpGet("SuitableAsync")] 79 | public async Task SuitableAsync() 80 | { 81 | await Task.CompletedTask; 82 | return Random.Shared.Next(-20, 55) >= 20; 83 | } 84 | 85 | [HttpGet("Empty")] 86 | public void Empty() 87 | { 88 | } 89 | 90 | [HttpGet("EmptyAsync")] 91 | public async Task EmptyAsync() 92 | { 93 | await Task.CompletedTask; 94 | } 95 | 96 | [HttpPost] 97 | public async Task Post(WeatherForecast forecast) 98 | { 99 | await Task.CompletedTask; 100 | return forecast; 101 | } 102 | } -------------------------------------------------------------------------------- /samples/DefaultWrapperSample/DefaultWrapperSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /samples/DefaultWrapperSample/Program.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | 7 | builder.Services.AddControllers().AddResponseWrapper(); 8 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 9 | builder.Services.AddEndpointsApiExplorer(); 10 | builder.Services.AddSwaggerGen(); 11 | 12 | var app = builder.Build(); 13 | 14 | // Configure the HTTP request pipeline. 15 | if (app.Environment.IsDevelopment()) 16 | { 17 | app.UseSwagger(); 18 | app.UseSwaggerUI(); 19 | } 20 | 21 | app.UseHttpsRedirection(); 22 | 23 | app.UseAuthorization(); 24 | 25 | app.MapControllers(); 26 | 27 | app.Run(); -------------------------------------------------------------------------------- /samples/DefaultWrapperSample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:52332", 8 | "sslPort": 44378 9 | } 10 | }, 11 | "profiles": { 12 | "DefaultWrapperSample": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7238;http://localhost:5238", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /samples/DefaultWrapperSample/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace DefaultWrapperSample; 2 | 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } -------------------------------------------------------------------------------- /samples/DefaultWrapperSample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /samples/DefaultWrapperSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/Abstractions/DisableWrapperAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AspNetCore.ResponseWrapper.Abstractions 4 | { 5 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 6 | public class DisableWrapperAttribute : Attribute, IDisableWrapperMetadata 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/Abstractions/IDisableWrapperMetadata.cs: -------------------------------------------------------------------------------- 1 | namespace AspNetCore.ResponseWrapper.Abstractions 2 | { 3 | public interface IDisableWrapperMetadata 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/Abstractions/IResponseWrapper.cs: -------------------------------------------------------------------------------- 1 | namespace AspNetCore.ResponseWrapper.Abstractions 2 | { 3 | public interface IResponseWrapper 4 | { 5 | IResponseWrapper Ok(); 6 | 7 | IResponseWrapper BusinessError(string message); 8 | 9 | IResponseWrapper ClientError(string message); 10 | } 11 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/Abstractions/IResponseWrapper`.cs: -------------------------------------------------------------------------------- 1 | namespace AspNetCore.ResponseWrapper.Abstractions 2 | { 3 | public interface IResponseWrapper : IResponseWrapper 4 | { 5 | IResponseWrapper Ok(TResponse response); 6 | } 7 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/AspNetCore.ResponseWrapper.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0;net6.0 5 | 1.0.1 6 | enable 7 | Library 8 | true 9 | true 10 | Asp.Net core response wrapper 11 | MIT 12 | logo.png 13 | https://github.com/huiyuanai709/AspNetCore.ResponseWrapper 14 | README.md 15 | AspNetCore HTTP Response Wrapper 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/Mvc/Abstractions/IResultWrapperFilter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Filters; 2 | 3 | namespace AspNetCore.ResponseWrapper.Mvc.Abstractions 4 | { 5 | /// 6 | /// A filter that allows response wrap. 7 | /// 8 | public interface IResultWrapperFilter : IActionFilter 9 | { 10 | } 11 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/Mvc/Filters/ModelInvalidWrapperFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using AspNetCore.ResponseWrapper.Abstractions; 4 | using Microsoft.AspNetCore.Http; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.AspNetCore.Mvc.Filters; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace AspNetCore.ResponseWrapper.Mvc.Filters 10 | { 11 | public class ModelInvalidWrapperFilter : IActionFilter 12 | { 13 | private readonly IResponseWrapper _responseWrapper; 14 | private readonly ILogger _logger; 15 | 16 | public ModelInvalidWrapperFilter(IResponseWrapper responseWrapper, ILoggerFactory loggerFactory) 17 | { 18 | _responseWrapper = responseWrapper; 19 | _logger = loggerFactory.CreateLogger(); 20 | } 21 | 22 | private static readonly Action ModelStateInvalidFilterExecuting = LoggerMessage.Define( 23 | LogLevel.Debug, 24 | new EventId(1, "ModelStateInvalidFilterExecuting"), 25 | "The request has model state errors, returning an error response."); 26 | 27 | public void OnActionExecuting(ActionExecutingContext context) 28 | { 29 | if (context.Result == null && !context.ModelState.IsValid) 30 | { 31 | ModelStateInvalidFilterExecuting(_logger, null); 32 | context.Result = new ObjectResult(_responseWrapper.ClientError(string.Join(",", 33 | context.ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)))) 34 | { 35 | StatusCode = StatusCodes.Status400BadRequest 36 | }; 37 | } 38 | } 39 | 40 | public void OnActionExecuted(ActionExecutedContext context) 41 | { 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/Mvc/Filters/ResultWrapperFilter.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper.Abstractions; 2 | using AspNetCore.ResponseWrapper.Mvc.Abstractions; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.AspNetCore.Mvc.Filters; 5 | 6 | namespace AspNetCore.ResponseWrapper.Mvc.Filters 7 | { 8 | public class ResultWrapperFilter : IResultWrapperFilter 9 | { 10 | private readonly IResponseWrapper _responseWrapper; 11 | private readonly IResponseWrapper _responseWithDataWrapper; 12 | 13 | public ResultWrapperFilter(IResponseWrapper responseWrapper, IResponseWrapper responseWithDataWrapper) 14 | { 15 | _responseWrapper = responseWrapper; 16 | _responseWithDataWrapper = responseWithDataWrapper; 17 | } 18 | 19 | public void OnActionExecuting(ActionExecutingContext context) 20 | { 21 | } 22 | 23 | public void OnActionExecuted(ActionExecutedContext context) 24 | { 25 | switch (context.Result) 26 | { 27 | case EmptyResult: 28 | context.Result = new OkObjectResult(_responseWrapper.Ok()); 29 | return; 30 | case ObjectResult objectResult: 31 | context.Result = new OkObjectResult(_responseWithDataWrapper.Ok(objectResult.Value)); 32 | return; 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/ResponseWrapper.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper.Abstractions; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace AspNetCore.ResponseWrapper 5 | { 6 | /// 7 | /// Default wrapper for or error occured 8 | /// 9 | public class ResponseWrapper : IResponseWrapper 10 | { 11 | public int Code { get; } 12 | 13 | public string? Message { get; } 14 | 15 | public ResponseWrapper() 16 | { 17 | } 18 | 19 | protected ResponseWrapper(int code, string? message) 20 | { 21 | Code = code; 22 | Message = message; 23 | } 24 | 25 | public IResponseWrapper Ok() 26 | { 27 | return new ResponseWrapper(ResponseWrapperDefaults.OkCode, null); 28 | } 29 | 30 | public IResponseWrapper BusinessError(string message) 31 | { 32 | return new ResponseWrapper(ResponseWrapperDefaults.BusinessErrorCode, message); 33 | } 34 | 35 | public IResponseWrapper ClientError(string message) 36 | { 37 | return new ResponseWrapper(ResponseWrapperDefaults.ClientErrorCode, message); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/ResponseWrapperApplicationModelProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Reflection; 4 | using System.Threading.Tasks; 5 | using AspNetCore.ResponseWrapper.Abstractions; 6 | using AspNetCore.ResponseWrapper.Mvc.Filters; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.AspNetCore.Mvc.ApplicationModels; 10 | using Microsoft.AspNetCore.Mvc.Infrastructure; 11 | using Microsoft.Extensions.Logging; 12 | using Microsoft.Extensions.Options; 13 | 14 | namespace AspNetCore.ResponseWrapper 15 | { 16 | public class ResponseWrapperApplicationModelProvider : IApplicationModelProvider 17 | { 18 | private readonly ILoggerFactory _loggerFactory; 19 | private readonly IResponseWrapper _responseWrapper; 20 | private readonly Type _responseWrapperType; 21 | private readonly IResponseWrapper _genericResponseWrapper; 22 | private readonly Type _genericWrapperType; 23 | private readonly bool _suppressModelInvalidWrapper; 24 | private readonly bool _onlyAvailableInApiController; 25 | 26 | public ResponseWrapperApplicationModelProvider(IOptions responseWrapperOptions, 27 | ILoggerFactory loggerFactory) 28 | { 29 | var options = responseWrapperOptions.Value; 30 | _loggerFactory = loggerFactory; 31 | _responseWrapper = options.ResponseWrapper; 32 | _responseWrapperType = options.ResponseWrapper.GetType(); 33 | _genericResponseWrapper = options.GenericResponseWrapper; 34 | _genericWrapperType = options.GenericResponseWrapper.GetType().GetGenericTypeDefinition(); 35 | _suppressModelInvalidWrapper = options.SuppressModelInvalidWrapper; 36 | _onlyAvailableInApiController = options.OnlyAvailableInApiController; 37 | } 38 | 39 | public int Order => -1000 + 20; 40 | 41 | public void OnProvidersExecuted(ApplicationModelProviderContext context) 42 | { 43 | // Intentionally empty. 44 | } 45 | 46 | public void OnProvidersExecuting(ApplicationModelProviderContext context) 47 | { 48 | if (context is null) 49 | { 50 | throw new ArgumentNullException(nameof(context)); 51 | } 52 | 53 | foreach (var controllerModel in context.Result.Controllers) 54 | { 55 | if (_onlyAvailableInApiController && IsApiController(controllerModel)) 56 | { 57 | continue; 58 | } 59 | 60 | if (controllerModel.Attributes.OfType().Any()) 61 | { 62 | if (!_suppressModelInvalidWrapper) 63 | { 64 | foreach (var actionModel in controllerModel.Actions) 65 | { 66 | actionModel.Filters.Add(new ModelInvalidWrapperFilter(_responseWrapper, _loggerFactory)); 67 | } 68 | } 69 | 70 | continue; 71 | } 72 | 73 | foreach (var actionModel in controllerModel.Actions) 74 | { 75 | if (!_suppressModelInvalidWrapper) 76 | { 77 | actionModel.Filters.Add(new ModelInvalidWrapperFilter(_responseWrapper, _loggerFactory)); 78 | } 79 | 80 | if (actionModel.Attributes.OfType().Any()) continue; 81 | actionModel.Filters.Add(new ResultWrapperFilter(_responseWrapper, _genericResponseWrapper)); 82 | AddResponseWrapperFilter(actionModel); 83 | } 84 | } 85 | } 86 | 87 | private void AddResponseWrapperFilter(ActionModel actionModel) 88 | { 89 | const int statusCode = StatusCodes.Status200OK; 90 | var responseType = actionModel.ActionMethod.ReturnType; 91 | if (responseType.IsAssignableTo(typeof(IConvertToActionResult))) 92 | { 93 | AddIActionResultWrapperFilter(responseType); 94 | return; 95 | } 96 | 97 | if (responseType == typeof(void) || responseType == typeof(Task)) 98 | { 99 | AddWrapperFilter(); 100 | return; 101 | } 102 | 103 | if (responseType.BaseType == typeof(Task)) 104 | { 105 | var genericArgument = responseType.GetGenericArguments()[0]; 106 | if (genericArgument.IsAssignableTo(typeof(IConvertToActionResult))) 107 | { 108 | AddIActionResultWrapperFilter(genericArgument); 109 | return; 110 | } 111 | 112 | AddGenericWrapperFilter(genericArgument); 113 | return; 114 | } 115 | 116 | AddGenericWrapperFilter(responseType); 117 | 118 | void AddWrapperFilter() 119 | { 120 | actionModel.Filters.Add(new ProducesResponseTypeAttribute(_responseWrapperType, statusCode)); 121 | } 122 | 123 | void AddGenericWrapperFilter(Type type) 124 | { 125 | actionModel.Filters.Add( 126 | new ProducesResponseTypeAttribute(_genericWrapperType.MakeGenericType(type), statusCode)); 127 | } 128 | 129 | // Add wrapper filter for the type is assignable to IConvertToActionResult 130 | void AddIActionResultWrapperFilter(Type type) 131 | { 132 | if (type.GetGenericArguments().Any()) 133 | { 134 | var genericType = type.GetGenericArguments()[0]; 135 | AddGenericWrapperFilter(genericType); 136 | return; 137 | } 138 | 139 | AddWrapperFilter(); 140 | } 141 | } 142 | 143 | private static bool IsApiController(ControllerModel controller) 144 | { 145 | if (controller.Attributes.OfType().Any()) 146 | { 147 | return true; 148 | } 149 | 150 | var controllerAssembly = controller.ControllerType.Assembly; 151 | var assemblyAttributes = controllerAssembly.GetCustomAttributes(); 152 | return assemblyAttributes.OfType().Any(); 153 | } 154 | } 155 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/ResponseWrapperBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Mvc.ApplicationModels; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.DependencyInjection.Extensions; 5 | 6 | namespace AspNetCore.ResponseWrapper 7 | { 8 | public static class ResponseWrapperBuilderExtensions 9 | { 10 | public static IMvcBuilder AddResponseWrapper(this IMvcBuilder mvcBuilder) 11 | { 12 | return AddResponseWrapper(mvcBuilder, _ => {}); 13 | } 14 | 15 | public static IMvcBuilder AddResponseWrapper(this IMvcBuilder mvcBuilder, Action action) 16 | { 17 | mvcBuilder.Services.Configure(action); 18 | mvcBuilder.ConfigureApiBehaviorOptions(options => 19 | { 20 | options.SuppressModelStateInvalidFilter = true; 21 | }); 22 | mvcBuilder.Services.TryAddEnumerable(ServiceDescriptor.Transient()); 23 | return mvcBuilder; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/ResponseWrapperDefaults.cs: -------------------------------------------------------------------------------- 1 | namespace AspNetCore.ResponseWrapper 2 | { 3 | public static class ResponseWrapperDefaults 4 | { 5 | #region Code constants 6 | 7 | /// 8 | /// This indicate work normally 9 | /// 10 | public const int OkCode = 0; 11 | 12 | /// 13 | /// This indicate business error occured 14 | /// 15 | public const int BusinessErrorCode = 1; 16 | 17 | /// 18 | /// This indicate client bad request, model invalid mostly 19 | /// 20 | public const int ClientErrorCode = 400; 21 | 22 | /// 23 | /// The indicate server error occured, unhandled exception mostly 24 | /// 25 | public const int ServerErrorCode = 500; 26 | 27 | #endregion 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/ResponseWrapperOptions.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper.Abstractions; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace AspNetCore.ResponseWrapper 5 | { 6 | public class ResponseWrapperOptions 7 | { 8 | /// 9 | /// A wrapper for no business data return, Set to change the default wrapper 10 | /// 11 | public IResponseWrapper ResponseWrapper { get; set; } = new ResponseWrapper(); 12 | 13 | /// 14 | /// A wrapper for business data return, Set to change the default wrapper 15 | /// 16 | public IResponseWrapper GenericResponseWrapper { get; set; } = new ResponseWrapper(); 17 | 18 | /// 19 | /// Gets or sets a value that determines if the filter that returns an when 20 | /// is invalid is suppressed. 21 | /// 22 | public bool SuppressModelInvalidWrapper { get; set; } 23 | 24 | /// 25 | /// Gets or sets a value that determines response wrapper only available in ApiController. 26 | /// 27 | public bool OnlyAvailableInApiController { get; set; } 28 | } 29 | } -------------------------------------------------------------------------------- /src/AspNetCore.ResponseWrapper/ResponseWrapper`.cs: -------------------------------------------------------------------------------- 1 | using AspNetCore.ResponseWrapper.Abstractions; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace AspNetCore.ResponseWrapper 5 | { 6 | /// 7 | /// Default wrapper for 8 | /// 9 | /// 10 | public class ResponseWrapper : ResponseWrapper, IResponseWrapper 11 | { 12 | public TResponse? Data { get; } 13 | 14 | public ResponseWrapper() 15 | { 16 | } 17 | 18 | private ResponseWrapper(int code, string? message, TResponse? data) : base(code, message) 19 | { 20 | Data = data; 21 | } 22 | 23 | public IResponseWrapper Ok(TResponse response) 24 | { 25 | return new ResponseWrapper(ResponseWrapperDefaults.OkCode, null, response); 26 | } 27 | } 28 | } --------------------------------------------------------------------------------