Skip to content

Instantly share code, notes, and snippets.

@scheffler
Last active June 26, 2019 19:14
Show Gist options
  • Save scheffler/4cf83d9281109ba8170ce4357d2fa21b to your computer and use it in GitHub Desktop.
Save scheffler/4cf83d9281109ba8170ce4357d2fa21b to your computer and use it in GitHub Desktop.
ASP.Net Core Snippets

Nuget packages when working in aspnet core

Automapper

Package: AutoMapper.Extensions.Microsoft.DependencyInjection

In Startup\ConfgureServices:

servcies.AddAutomapper();

In Data\Models dir:

Create a ModelProfile class which inherits from Pofile. 
In the constructor calls `CreateMap` and pass in the from and to classes

In Controller class:

Use constructor injection to add an IMapper

API Versioning

Microsoft.AspNetcore.Mvc.Versioning

Startup.cs\ConfigureServices

services.AddApiVersioning()
services.AddMvc(opt=> opt.EnableEndpointrouting=false)  // issue with 2.2

Startup.cs ConfigureServices

Registers PortalService with DI so that controllers can get this via Constructor

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    var connstring = Configuration.GetConnectionString("Portal");

    services.AddScoped(x => {
        var opts = new DbContextOptionsBuilder<PortalDbContext>()
            .UseSqlServer(connstring)
            .Options;
        var ctx = new PortalDbContext(opts);
        return new PortalService(ctx);
    });

Set the directory for React build assets to be served from in production

    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/build";
    });

Auth0 Authentication

    string domain = $"https://{Configuration["Auth0:Domain"]}";
    var aud = Configuration["Auth0:ApiIdentifier"];

    services.AddAuthentication(opts =>
    {
        opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        options.Authority = domain;
        options.Audience = aud;
    });

Auth0 Authorization Support

    //services.AddAuthorization(opts =>
    //{
    //    opts.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
    //});

    //services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
       

Sample appsettings.json file

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Portal": "Server=localhost;Database=bankpoint_portal;Trusted_Connection=True;"
  },
  "Auth0": {
    "Domain": "tbkportal.auth0.com",
    "ApiIdentifier": "https://bankpoint.app/tbk"
  }

}

Startup.cs Configure

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            // Requires that you start the react dev server first
            if (env.IsDevelopment())
            {
                //spa.UseReactDevelopmentServer(npmScript: "start");
                spa.UseProxyToSpaDevelopmentServer("http://localhost:3000");
            }
        });
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment