├── global.json ├── src └── AspNetCoreTipsAndTricksSample │ ├── appsettings.json │ ├── wwwroot │ ├── web.config │ └── index.html │ ├── Responses │ ├── ValueResponse.cs │ └── ErrorResponse.cs │ ├── Services │ ├── IValueService.cs │ └── ValueService.cs │ ├── Properties │ └── launchSettings.json │ ├── Filters │ ├── SchemaDocumentFilter.cs │ ├── GlobalActionFilter.cs │ └── GlobalExceptionFilter.cs │ ├── AspNetCoreTipsAndTricksSample.xproj │ ├── Controllers │ └── ValuesController.cs │ ├── project.json │ ├── Exceptions │ └── HttpResponseException.cs │ └── Startup.cs ├── LICENSE ├── README.md ├── AspNetCoreTipsAndTricksSample.sln ├── AspNetCoreTipsAndTricksSample.sln.DotSettings ├── Settings.StyleCop └── .gitignore /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "projects": [ "src", "test" ], 3 | "sdk": { 4 | "version": "1.0.0-rc1-update1" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Verbose", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/wwwroot/web.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Responses/ValueResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace AspNetCoreTipsAndTricksSample.Responses 4 | { 5 | /// 6 | /// This represents the response entity for values. 7 | /// 8 | public class ValueResponse 9 | { 10 | /// 11 | /// Gets or sets the list of values. 12 | /// 13 | public IEnumerable Values { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Services/IValueService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using AspNetCoreTipsAndTricksSample.Responses; 4 | 5 | namespace AspNetCoreTipsAndTricksSample.Services 6 | { 7 | /// 8 | /// This provides interfaces to the class. 9 | /// 10 | public interface IValueService : IDisposable 11 | { 12 | /// 13 | /// Gets the list of values. 14 | /// 15 | /// Returns the object. 16 | ValueResponse GetValues(); 17 | } 18 | } -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Responses/ErrorResponse.cs: -------------------------------------------------------------------------------- 1 | #if !DEBUG 2 | using Newtonsoft.Json; 3 | #endif 4 | 5 | namespace AspNetCoreTipsAndTricksSample.Responses 6 | { 7 | /// 8 | /// This represents the response entity for error. 9 | /// 10 | public class ErrorResponse 11 | { 12 | /// 13 | /// Gets or sets the message. 14 | /// 15 | public string Message { get; set; } 16 | 17 | /// 18 | /// Gets or sets the stack trace. 19 | /// 20 | #if !DEBUG 21 | [JsonIgnore] 22 | #endif 23 | public string StackTrace { get; set; } 24 | } 25 | } -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "https://localhost:44390/", 7 | "sslPort": 44390 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "Hosting:Environment": "Development" 16 | } 17 | }, 18 | "web": { 19 | "commandName": "web", 20 | "environmentVariables": { 21 | "Hosting:Environment": "Development" 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Filters/SchemaDocumentFilter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | using Swashbuckle.SwaggerGen; 4 | 5 | namespace AspNetCoreTipsAndTricksSample.Filters 6 | { 7 | /// 8 | /// This represents the document filter entity for Swagger document. 9 | /// 10 | public class SchemaDocumentFilter : IDocumentFilter 11 | { 12 | /// 13 | /// Applies filter context to swagger document. 14 | /// 15 | /// instance. 16 | /// instance. 17 | public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) 18 | { 19 | swaggerDoc.Host = "localhost:44390"; 20 | swaggerDoc.BasePath = "/"; 21 | swaggerDoc.Schemes = new List() { "https" }; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Services/ValueService.cs: -------------------------------------------------------------------------------- 1 | using AspNetCoreTipsAndTricksSample.Responses; 2 | 3 | namespace AspNetCoreTipsAndTricksSample.Services 4 | { 5 | /// 6 | /// This represents the service entity for values. 7 | /// 8 | public class ValueService : IValueService 9 | { 10 | private bool _disposed; 11 | 12 | /// 13 | /// Gets the list of values. 14 | /// 15 | /// Returns the object. 16 | public ValueResponse GetValues() 17 | { 18 | var values = new[] { "value1", "value2" }; 19 | return new ValueResponse() { Values = values }; 20 | } 21 | 22 | /// 23 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 24 | /// 25 | public void Dispose() 26 | { 27 | if (this._disposed) 28 | { 29 | return; 30 | } 31 | 32 | this._disposed = true; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Dev Kimchi (http://devkimchi.com) 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 | # ASP.NET Core Tips & Tricks Sample # 2 | 3 | This provides a sample ASP.NET Core application with various tips and tricks 4 | 5 | 6 | ## License ## 7 | 8 | **ASP.NET Core Tips & Tricks Sample** is released under [MIT License](http://opensource.org/licenses/MIT) 9 | 10 | > The MIT License (MIT) 11 | > 12 | > Copyright (c) 2016 [DevKimchi](http://devkimchi.com) 13 | > 14 | > Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 15 | > 16 | > The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 17 | > 18 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/AspNetCoreTipsAndTricksSample.xproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 6cdfde54-f338-4a5b-a543-141c253a41ad 10 | AspNetCoreTipsAndTricksSample 11 | ..\..\artifacts\obj\$(MSBuildProjectName) 12 | ..\..\artifacts\bin\$(MSBuildProjectName)\ 13 | 14 | 15 | 2.0 16 | 17 | 18 | True 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using AspNetCoreTipsAndTricksSample.Responses; 4 | using AspNetCoreTipsAndTricksSample.Services; 5 | 6 | using Microsoft.AspNet.Mvc; 7 | 8 | namespace AspNetCoreTipsAndTricksSample.Controllers 9 | { 10 | /// 11 | /// This represents the controller entity for values. 12 | /// 13 | [Route("values")] 14 | public class ValuesController : Controller 15 | { 16 | private readonly IValueService _service; 17 | 18 | /// 19 | /// Initializes a new instance of the class. 20 | /// 21 | /// instance. 22 | public ValuesController(IValueService service) 23 | { 24 | if (service == null) 25 | { 26 | throw new ArgumentNullException(nameof(service)); 27 | } 28 | 29 | this._service = service; 30 | } 31 | 32 | /// 33 | /// Gets the list of values. 34 | /// 35 | /// Returns the list of values. 36 | [HttpGet] 37 | [Route("")] 38 | [Produces(typeof(ValueResponse))] 39 | public IActionResult Get() 40 | { 41 | var result = this._service.GetValues(); 42 | return this.Ok(result); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Filters/GlobalActionFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using Microsoft.AspNet.Mvc.Filters; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace AspNetCoreTipsAndTricksSample.Filters 7 | { 8 | /// 9 | /// This represents the filter attribute entity for global actions. 10 | /// 11 | public class GlobalActionFilter : ActionFilterAttribute 12 | { 13 | private readonly ILogger _logger; 14 | 15 | /// 16 | /// Initializes a new instance of the class. 17 | /// 18 | /// instance. 19 | public GlobalActionFilter(ILoggerFactory logger) 20 | { 21 | if (logger == null) 22 | { 23 | throw new ArgumentNullException(nameof(logger)); 24 | } 25 | 26 | this._logger = logger.CreateLogger("Global Action Filter"); 27 | } 28 | 29 | /// 30 | /// Called while an action is being executed. 31 | /// 32 | /// instance. 33 | public override void OnActionExecuting(ActionExecutingContext context) 34 | { 35 | base.OnActionExecuting(context); 36 | 37 | this._logger.LogInformation("Global Action Filter - OnActionExecuting"); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "compilationOptions": { 4 | "emitEntryPoint": true 5 | }, 6 | 7 | "dependencies": { 8 | "Autofac.Extensions.DependencyInjection": "4.0.0-rc1-177", 9 | "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final", 10 | "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", 11 | "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", 12 | "Microsoft.AspNet.Mvc.Abstractions": "6.0.0-rc1-final", 13 | "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", 14 | "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", 15 | "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final", 16 | "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final", 17 | "Microsoft.Extensions.Logging": "1.0.0-rc1-final", 18 | "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final", 19 | "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final", 20 | "Swashbuckle": "6.0.0-rc1-final" 21 | }, 22 | 23 | "commands": { 24 | "web": "Microsoft.AspNet.Server.Kestrel" 25 | }, 26 | 27 | "frameworks": { 28 | "dnx451": { }, 29 | "dnxcore50": { } 30 | }, 31 | 32 | "exclude": [ 33 | "wwwroot", 34 | "node_modules" 35 | ], 36 | "publishExclude": [ 37 | "**.user", 38 | "**.vspscc" 39 | ], 40 | 41 | "scripts": { 42 | "prepublish": "xcopy ..\\..\\artifacts\\bin\\AspNetCoreTipsAndTricksSample\\Debug\\dnx451\\AspNetCoreTipsAndTricksSample.xml", 43 | "postpublish": "del AspNetCoreTipsAndTricksSample.xml" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /AspNetCoreTipsAndTricksSample.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.24720.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{80D2A0A8-5418-45B2-BC70-E2F94E6482B7}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D9AD5843-A43E-4AC3-8D5B-0AFA700E61D9}" 9 | ProjectSection(SolutionItems) = preProject 10 | global.json = global.json 11 | EndProjectSection 12 | EndProject 13 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AspNetCoreTipsAndTricksSample", "src\AspNetCoreTipsAndTricksSample\AspNetCoreTipsAndTricksSample.xproj", "{6CDFDE54-F338-4A5B-A543-141C253A41AD}" 14 | EndProject 15 | Global 16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 17 | Debug|Any CPU = Debug|Any CPU 18 | Release|Any CPU = Release|Any CPU 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {6CDFDE54-F338-4A5B-A543-141C253A41AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {6CDFDE54-F338-4A5B-A543-141C253A41AD}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {6CDFDE54-F338-4A5B-A543-141C253A41AD}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {6CDFDE54-F338-4A5B-A543-141C253A41AD}.Release|Any CPU.Build.0 = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(SolutionProperties) = preSolution 27 | HideSolutionNode = FALSE 28 | EndGlobalSection 29 | GlobalSection(NestedProjects) = preSolution 30 | {6CDFDE54-F338-4A5B-A543-141C253A41AD} = {80D2A0A8-5418-45B2-BC70-E2F94E6482B7} 31 | EndGlobalSection 32 | EndGlobal 33 | -------------------------------------------------------------------------------- /AspNetCoreTipsAndTricksSample.sln.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | True 3 | False 4 | <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="AaBb_AaBb" /></Policy> 5 | <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy> 6 | True 7 | True 8 | True -------------------------------------------------------------------------------- /Settings.StyleCop: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | organisation 5 | git 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | False 14 | 15 | 16 | 17 | 18 | False 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | False 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | False 39 | 40 | 41 | 42 | 43 | True 44 | 45 | 46 | 47 | 48 | 49 | 50 | False 51 | 52 | 53 | 54 | 55 | 56 | db 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Exceptions/HttpResponseException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | #if DNXCORE50 5 | 6 | using ApplicationException = System.InvalidOperationException; 7 | 8 | #endif 9 | 10 | namespace AspNetCoreTipsAndTricksSample.Exceptions 11 | { 12 | /// 13 | /// This represents the exception entity for HTTP response. 14 | /// 15 | public class HttpResponseException : ApplicationException 16 | { 17 | /// 18 | /// Initializes a new instance of the class. 19 | /// 20 | /// value. 21 | public HttpResponseException(HttpStatusCode httpStatusCode) 22 | : base() 23 | { 24 | this.HttpStatusCode = httpStatusCode; 25 | } 26 | 27 | /// 28 | /// Initializes a new instance of the class. 29 | /// 30 | /// value. 31 | /// Exception message. 32 | public HttpResponseException(HttpStatusCode httpStatusCode, string message) 33 | : base(message) 34 | { 35 | this.HttpStatusCode = httpStatusCode; 36 | } 37 | 38 | /// 39 | /// Initializes a new instance of the class. 40 | /// 41 | /// value. 42 | /// Exception message. 43 | /// Inner object. 44 | public HttpResponseException(HttpStatusCode httpStatusCode, string message, Exception innerException) 45 | : base(message, innerException) 46 | { 47 | this.HttpStatusCode = httpStatusCode; 48 | } 49 | 50 | /// 51 | /// Gets or sets the value. 52 | /// 53 | public HttpStatusCode HttpStatusCode { get; set; } 54 | } 55 | } -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Filters/GlobalExceptionFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | using AspNetCoreTipsAndTricksSample.Exceptions; 5 | using AspNetCoreTipsAndTricksSample.Responses; 6 | 7 | using Microsoft.AspNet.Mvc; 8 | using Microsoft.AspNet.Mvc.Filters; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace AspNetCoreTipsAndTricksSample.Filters 12 | { 13 | /// 14 | /// This represents the filter entity for global exceptions. 15 | /// 16 | public class GlobalExceptionFilter : IExceptionFilter, IDisposable 17 | { 18 | private readonly ILogger _logger; 19 | 20 | private bool _disposed; 21 | 22 | /// 23 | /// Initializes a new instance of the class. 24 | /// 25 | /// instance. 26 | public GlobalExceptionFilter(ILoggerFactory logger) 27 | { 28 | if (logger == null) 29 | { 30 | throw new ArgumentNullException(nameof(logger)); 31 | } 32 | 33 | this._logger = logger.CreateLogger("Global Exception Filter"); 34 | } 35 | 36 | /// 37 | /// Performs while an exception arises. 38 | /// 39 | /// instance. 40 | public void OnException(ExceptionContext context) 41 | { 42 | var response = new ErrorResponse() { Message = context.Exception.Message }; 43 | #if DEBUG 44 | response.StackTrace = context.Exception.StackTrace; 45 | #endif 46 | context.Result = new ObjectResult(response) 47 | { 48 | StatusCode = GetHttpStatusCode(context.Exception), 49 | DeclaredType = typeof(ErrorResponse) 50 | }; 51 | 52 | this._logger.LogError("GlobalExceptionFilter", context.Exception); 53 | } 54 | 55 | /// 56 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. 57 | /// 58 | public void Dispose() 59 | { 60 | if (this._disposed) 61 | { 62 | return; 63 | } 64 | 65 | this._disposed = true; 66 | } 67 | 68 | private static int GetHttpStatusCode(Exception ex) 69 | { 70 | if (ex is HttpResponseException) 71 | { 72 | return (int)(ex as HttpResponseException).HttpStatusCode; 73 | } 74 | 75 | return (int)HttpStatusCode.InternalServerError; 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | 24 | # Visual Studio 2015 cache/options directory 25 | .vs/ 26 | # Uncomment if you have tasks that create the project's static files in wwwroot 27 | #wwwroot/ 28 | 29 | # MSTest test Results 30 | [Tt]est[Rr]esult*/ 31 | [Bb]uild[Ll]og.* 32 | 33 | # NUNIT 34 | *.VisualState.xml 35 | TestResult.xml 36 | 37 | # Build Results of an ATL Project 38 | [Dd]ebugPS/ 39 | [Rr]eleasePS/ 40 | dlldata.c 41 | 42 | # DNX 43 | project.lock.json 44 | artifacts/ 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | # NuGet v3's project.json files produces more ignoreable files 154 | *.nuget.props 155 | *.nuget.targets 156 | 157 | # Microsoft Azure Build Output 158 | csx/ 159 | *.build.csdef 160 | 161 | # Microsoft Azure Emulator 162 | ecf/ 163 | rcf/ 164 | 165 | # Microsoft Azure ApplicationInsights config file 166 | ApplicationInsights.config 167 | 168 | # Windows Store app package directory 169 | AppPackages/ 170 | BundleArtifacts/ 171 | 172 | # Visual Studio cache files 173 | # files ending in .cache can be ignored 174 | *.[Cc]ache 175 | # but keep track of directories ending in .cache 176 | !*.[Cc]ache/ 177 | 178 | # Others 179 | ClientBin/ 180 | ~$* 181 | *~ 182 | *.dbmdl 183 | *.dbproj.schemaview 184 | *.pfx 185 | *.publishsettings 186 | node_modules/ 187 | orleans.codegen.cs 188 | 189 | # RIA/Silverlight projects 190 | Generated_Code/ 191 | 192 | # Backup & report files from converting an old project file 193 | # to a newer Visual Studio version. Backup files are not needed, 194 | # because we have git ;-) 195 | _UpgradeReport_Files/ 196 | Backup*/ 197 | UpgradeLog*.XML 198 | UpgradeLog*.htm 199 | 200 | # SQL Server files 201 | *.mdf 202 | *.ldf 203 | 204 | # Business Intelligence projects 205 | *.rdl.data 206 | *.bim.layout 207 | *.bim_*.settings 208 | 209 | # Microsoft Fakes 210 | FakesAssemblies/ 211 | 212 | # GhostDoc plugin setting file 213 | *.GhostDoc.xml 214 | 215 | # Node.js Tools for Visual Studio 216 | .ntvs_analysis.dat 217 | 218 | # Visual Studio 6 build log 219 | *.plg 220 | 221 | # Visual Studio 6 workspace options file 222 | *.opt 223 | 224 | # Visual Studio LightSwitch build output 225 | **/*.HTMLClient/GeneratedArtifacts 226 | **/*.DesktopClient/GeneratedArtifacts 227 | **/*.DesktopClient/ModelManifest.xml 228 | **/*.Server/GeneratedArtifacts 229 | **/*.Server/ModelManifest.xml 230 | _Pvt_Extensions 231 | 232 | # Paket dependency manager 233 | .paket/paket.exe 234 | 235 | # FAKE - F# Make 236 | .fake/ 237 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Welcome to ASP.NET 5 6 | 127 | 128 | 129 | 130 | 138 | 139 |
140 |
141 |

This application consists of:

142 |
    143 |
  • Sample pages using ASP.NET MVC 6
  • 144 |
  • Gulp and Bower for managing client-side libraries
  • 145 |
  • Theming using Bootstrap
  • 146 |
147 |
148 | 160 | 172 | 181 | 182 | 185 |
186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /src/AspNetCoreTipsAndTricksSample/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Reflection; 7 | 8 | using AspNetCoreTipsAndTricksSample.Filters; 9 | using AspNetCoreTipsAndTricksSample.Services; 10 | 11 | using Autofac; 12 | using Autofac.Extensions.DependencyInjection; 13 | 14 | using Microsoft.AspNet.Builder; 15 | using Microsoft.AspNet.Diagnostics; 16 | using Microsoft.AspNet.Hosting; 17 | using Microsoft.AspNet.Http; 18 | using Microsoft.AspNet.Http.Features; 19 | using Microsoft.Extensions.Configuration; 20 | using Microsoft.Extensions.DependencyInjection; 21 | using Microsoft.Extensions.Logging; 22 | using Microsoft.Extensions.PlatformAbstractions; 23 | 24 | using Newtonsoft.Json; 25 | using Newtonsoft.Json.Converters; 26 | using Newtonsoft.Json.Serialization; 27 | 28 | using Swashbuckle.SwaggerGen; 29 | using Swashbuckle.SwaggerGen.XmlComments; 30 | 31 | namespace AspNetCoreTipsAndTricksSample 32 | { 33 | /// 34 | /// This represents the main entry point of the web application. 35 | /// 36 | public class Startup 37 | { 38 | private const string ExceptionsOnStartup = "Startup"; 39 | private const string ExceptionsOnConfigureServices = "ConfigureServices"; 40 | 41 | private readonly Dictionary> _exceptions; 42 | 43 | /// 44 | /// Initializes a new instance of the class. 45 | /// 46 | /// instance. 47 | /// instance. 48 | /// instance. 49 | /// List of arguments from the command line. 50 | public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory logger, string[] args = null) 51 | { 52 | this._exceptions = new Dictionary> 53 | { 54 | { ExceptionsOnStartup, new List() }, 55 | { ExceptionsOnConfigureServices, new List() }, 56 | }; 57 | 58 | try 59 | { 60 | this.HostingEnvironment = env; 61 | this.ApplicationEnvironment = appEnv; 62 | this.LoggerFactory = logger; 63 | 64 | var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json").AddEnvironmentVariables(); 65 | 66 | if (args != null && args.Length > 0) 67 | { 68 | builder.AddCommandLine(args); 69 | } 70 | 71 | this.Configuration = builder.Build(); 72 | } 73 | catch (Exception ex) 74 | { 75 | this._exceptions[ExceptionsOnStartup].Add(ex); 76 | } 77 | } 78 | 79 | /// 80 | /// Gets the instance. 81 | /// 82 | public IApplicationEnvironment ApplicationEnvironment { get; } 83 | 84 | /// 85 | /// Gets the instance. 86 | /// 87 | public IConfigurationRoot Configuration { get; set; } 88 | 89 | /// 90 | /// Gets the instance. 91 | /// 92 | public IHostingEnvironment HostingEnvironment { get; } 93 | 94 | /// 95 | /// Gets the instance. 96 | /// 97 | public ILoggerFactory LoggerFactory { get; } 98 | 99 | /// 100 | /// Defines the main entry point of the web application. 101 | /// 102 | /// List of arguments. 103 | public static void Main(string[] args) => WebApplication.Run(args); 104 | 105 | /// 106 | /// Configures modules. 107 | /// 108 | /// instance. 109 | /// instance. 110 | /// instance. 111 | /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 112 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) 113 | { 114 | logger.AddConsole(this.Configuration.GetSection("Logging")); 115 | logger.AddDebug(); 116 | 117 | var log = logger.CreateLogger(); 118 | if (this._exceptions.Any(p => p.Value.Any())) 119 | { 120 | app.Run( 121 | async context => 122 | { 123 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 124 | context.Response.ContentType = "text/plain"; 125 | 126 | foreach (var ex in this._exceptions) 127 | { 128 | foreach (var val in ex.Value) 129 | { 130 | log.LogError($"{ex.Key}:::{val.Message}"); 131 | await context.Response.WriteAsync($"Error on {ex.Key}: {val.Message}").ConfigureAwait(false); 132 | } 133 | } 134 | }); 135 | return; 136 | } 137 | 138 | try 139 | { 140 | app.UseExceptionHandler( 141 | builder => 142 | { 143 | builder.Run( 144 | async context => 145 | { 146 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 147 | context.Response.ContentType = "text/html"; 148 | 149 | var error = context.Features.Get(); 150 | if (error != null) 151 | { 152 | await context.Response.WriteAsync($"

Error: {error.Error.Message}

").ConfigureAwait(false); 153 | } 154 | }); 155 | }); 156 | 157 | app.UseIISPlatformHandler(); 158 | 159 | app.UseDefaultFiles(); 160 | app.UseStaticFiles(); 161 | 162 | app.UseMvc(); 163 | 164 | app.UseSwaggerGen(); 165 | app.UseSwaggerUi(); 166 | } 167 | catch (Exception ex) 168 | { 169 | app.Run( 170 | async context => 171 | { 172 | log.LogError($"{ex.Message}"); 173 | 174 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 175 | context.Response.ContentType = "text/plain"; 176 | await context.Response.WriteAsync(ex.Message).ConfigureAwait(false); 177 | await context.Response.WriteAsync(ex.StackTrace).ConfigureAwait(false); 178 | }); 179 | } 180 | } 181 | 182 | /// 183 | /// Configures services including dependencies. 184 | /// 185 | /// instance. 186 | /// This method gets called by the runtime. Use this method to add services to the container. 187 | public IServiceProvider ConfigureServices(IServiceCollection services) 188 | { 189 | try 190 | { 191 | this.ConfigureMvc(services, this.LoggerFactory); 192 | this.ConfigureSwagger(services, this.ApplicationEnvironment); 193 | 194 | return this.ConfigureDependencies(services); 195 | } 196 | catch (Exception ex) 197 | { 198 | this._exceptions[ExceptionsOnConfigureServices].Add(ex); 199 | return null; 200 | } 201 | } 202 | 203 | private static string GetXmlPath(IApplicationEnvironment appEnv) 204 | { 205 | var assembly = typeof(Startup).GetTypeInfo().Assembly; 206 | var assemblyName = assembly.GetName().Name; 207 | 208 | var path = $@"{appEnv.ApplicationBasePath}\{assemblyName}.xml"; 209 | if (File.Exists(path)) 210 | { 211 | return path; 212 | } 213 | 214 | var config = appEnv.Configuration; 215 | var runtime = $"{appEnv.RuntimeFramework.Identifier.ToLower()}{appEnv.RuntimeFramework.Version.ToString().Replace(".", string.Empty)}"; 216 | 217 | path = $@"{appEnv.ApplicationBasePath}\..\..\artifacts\bin\{assemblyName}\{config}\{runtime}\{assemblyName}.xml"; 218 | return path; 219 | } 220 | 221 | private IServiceProvider ConfigureDependencies(IServiceCollection services) 222 | { 223 | // services.AddTransient(); 224 | var builder = new ContainerBuilder(); 225 | 226 | builder.RegisterType().As(); 227 | 228 | builder.Populate(services); 229 | 230 | var container = builder.Build(); 231 | return container.Resolve(); 232 | } 233 | 234 | private void ConfigureMvc(IServiceCollection services, ILoggerFactory logger) 235 | { 236 | var builder = services.AddMvc(); 237 | 238 | builder.AddJsonOptions( 239 | o => 240 | { 241 | o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 242 | o.SerializerSettings.Converters.Add(new StringEnumConverter()); 243 | o.SerializerSettings.Formatting = Formatting.Indented; 244 | o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; 245 | o.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore; 246 | }); 247 | 248 | // Setup glogal action filters 249 | builder.AddMvcOptions(o => { o.Filters.Add(new GlobalActionFilter(logger)); }); 250 | 251 | // Setup global exception filters 252 | builder.AddMvcOptions(o => { o.Filters.Add(new GlobalExceptionFilter(logger)); }); 253 | } 254 | 255 | private void ConfigureSwagger(IServiceCollection services, IApplicationEnvironment appEnv) 256 | { 257 | services.AddSwaggerGen(); 258 | 259 | services.ConfigureSwaggerDocument( 260 | options => 261 | { 262 | options.SingleApiVersion(new Info() { Version = "v1", Title = "Swagger UI" }); 263 | options.IgnoreObsoleteActions = true; 264 | options.OperationFilter(new ApplyXmlActionComments(GetXmlPath(appEnv))); 265 | options.DocumentFilter(); 266 | }); 267 | 268 | services.ConfigureSwaggerSchema( 269 | options => 270 | { 271 | options.DescribeAllEnumsAsStrings = true; 272 | options.IgnoreObsoleteProperties = true; 273 | options.CustomSchemaIds(type => type.FriendlyId(true)); 274 | options.ModelFilter(new ApplyXmlTypeComments(GetXmlPath(appEnv))); 275 | }); 276 | } 277 | } 278 | } --------------------------------------------------------------------------------