项目作者: sulmar

项目描述 :
Przykłady ze szkolenia .NET Core 2.2
高级语言: C#
项目地址: git://github.com/sulmar/altkom-ebicom-dotnet-core.git
创建时间: 2019-10-07T14:02:20Z
项目社区:https://github.com/sulmar/altkom-ebicom-dotnet-core

开源协议:

下载


.NET Core

Przydatne komendy CLI

  • dotnet --list-sdks - wyświetlenie listy zainstalowanych SDK
  • dotnet new globaljson - utworzenie pliku global.json
  • dotnet new globaljson --sdk-version {version} - utworzenie pliku global.json i ustawienie wersji SDK
  • dotnet new --list - wyświetlenie listy dostępnych szablonów
  • dotnet new {template} - utworzenie nowego projektu na podstawie wybranego szablonu
  • dotnet new {template} -o {output} - utworzenie nowego projektu w podanym katalogu
  • dotnet restore - pobranie bibliotek nuget na podstawie pliku projektu
  • dotnet build - kompilacja projektu
  • dotnet run - uruchomienie projektu
  • dotnet run {app.dll} - uruchomienie aplikacji
  • dotnet test - uruchomienie testów jednostkowych
  • dotnet run watch - uruchomienie projektu w trybie śledzenia zmian
  • dotnet test - uruchomienie testów jednostkowych w trybie śledzenia zmian
  • dotnet add {project.csproj} reference {library.csproj} - dodanie odwołania do biblioteki
  • dotnet remove {project.csproj} reference {library.csproj} - usunięcie odwołania do biblioteki
  • dotnet new sln - utworzenie nowego rozwiązania
  • dotnet sln {solution.sln} add {project.csproj} - dodanie projektu do rozwiązania
  • dotnet sln {solution.sln} remove {project.csproj} - usunięcie projektu z rozwiązania
  • dotnet publish -c Release -r {platform} - publikacja aplikacji
  • dotnet publish -c Release -r win10-x64 - publikacja aplikacji dla Windows
  • dotnet publish -c Release -r linux-x64 - publikacja aplikacji dla Linux
  • dotnet publish -c Release -r osx-x64 - publikacja aplikacji dla MacOS
  • dotnet add package {package-name} - dodanie pakietu nuget do projektu
  • dotnet remove package {package-name} - usunięcie pakietu nuget do projektu

Konfiguracja

  • Utworzenie klasy opcji
    1. public class CustomerOptions
    2. {
    3. public int Quantity { get; set; }
    4. }
  • Plik konfiguracyjny appsettings.json
  1. {
  2. "CustomersModule": {
  3. "Quantity": 40
  4. },
  • Instalacja biblioteki
  1. dotnet add package Microsoft.Extensions.Options
  • Użycie opcji
  1. public class FakeCustomersService
  2. {
  3. private readonly CustomerOptions options;
  4. public FakeCustomersService(IOptions<CustomerOptions> options)
  5. {
  6. this.options = options.Value;
  7. }
  8. }
  • Konfiguracja opcji
  1. public class Startup
  2. {
  3. public IConfiguration Configuration { get; }
  4. public Startup(IHostingEnvironment env)
  5. {
  6. var builder = new ConfigurationBuilder()
  7. .SetBasePath(env.ContentRootPath)
  8. .AddJsonFile("appsettings.json", optional: false)
  9. .AddXmlFile("appsettings.xml", optional: true)
  10. .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
  11. Configuration = builder.Build();
  12. }
  13. public void ConfigureServices(IServiceCollection services)
  14. {
  15. services.Configure<CustomerOptions>(Configuration.GetSection("CustomersModule"));
  16. }
  17. }
  • Konfiguracja bez interfejsu IOptions
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. var customerOptions = new CustomerOptions();
  4. Configuration.GetSection("CustomersModule").Bind(customerOptions);
  5. services.AddSingleton(customerOptions);
  6. services.Configure<CustomerOptions>(Configuration.GetSection("CustomersModule"));
  7. }

REST API

Akcja Opis
GET Pobierz
POST Utwórz
PUT Podmień
DELETE Usuń
PATCH Zmień częściowo
HEAD Czy zasób istnieje

Opcje serializacji json

Plik Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddMvc()
  4. .AddJsonOptions(options =>
  5. {
  6. options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; // Wyłączenie generowania wartości null w jsonie
  7. options.SerializerSettings.Converters.Add(new StringEnumConverter(camelCaseText: true)); // Serializacja enum jako tekst
  8. options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // Zapobieganie cyklicznej serializacji
  9. })
  10. }

Włączenie obsługi XML

  • Instalacja
    1. dotnet add package AddXmlSerializerFormatters

Plik Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services
  4. .AddMvc(options => options.RespectBrowserAcceptHeader = true)
  5. .AddXmlSerializerFormatters();
  6. }

Przekazywanie formatu poprzez adres URL

  1. // GET api/customers/10
  2. // GET api/customers/10.json
  3. // GET api/customers/10.xml
  4. [Route("api/[controller]")]
  5. public class CustomersController : ControllerBase
  6. {
  7. [FormatFilter]
  8. [HttpGet("{id:int}.{format?}")]
  9. public IActionResult GetById(int id)
  10. {
  11. if (!customerRepository.IsExists(id))
  12. return NotFound();
  13. var customer = customerRepository.Get(id);
  14. return Ok(customer);
  15. }
  16. }

Autentyfikacja

Basic

Headers

Key Value
Authorization Basic {Base64(login:password)}

Utworzenie uchwytu

  1. public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
  2. {
  3. private readonly IUsersService usersService;
  4. public BasicAuthenticationHandler(
  5. IUsersService usersService,
  6. IOptionsMonitor<AuthenticationSchemeOptions> options,
  7. ILoggerFactory logger,
  8. UrlEncoder encoder,
  9. ISystemClock clock) : base(options, logger, encoder, clock)
  10. {
  11. this.usersService = usersService;
  12. }
  13. protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
  14. {
  15. if (!Request.Headers.ContainsKey("Authorization"))
  16. {
  17. return AuthenticateResult.Fail("Missing authorization header");
  18. }
  19. var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
  20. var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
  21. var credentials = Encoding.UTF8.GetString(credentialBytes).Split(":");
  22. var username = credentials[0];
  23. var password = credentials[1];
  24. User user = usersService.Authenticate(username, password);
  25. if (user == null)
  26. {
  27. return AuthenticateResult.Fail("Invalid username or password");
  28. }
  29. IIdentity identity = new ClaimsIdentity(Scheme.Name);
  30. ClaimsPrincipal principal = new ClaimsPrincipal(identity);
  31. // IIdentity identity = new GenericIdentity(user.Login);
  32. var ticket = new AuthenticationTicket(principal, Scheme.Name);
  33. return AuthenticateResult.Success(ticket);
  34. }
  35. }

Rejestracja

Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddAuthentication("BasicAuthorization")
  4. .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthorization", null);
  5. }
  6. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  7. {
  8. app.UseAuthentication();
  9. app.UseMvc();
  10. }

Token

Headers

Key Value
Authorization Bearer {token}

JWT

https://github.com/sulmar/dotnet-core-jwt

OWIN

Startup.cs

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. app.UseOwin(pipeline => pipeline(next => OwinHandler));
  4. }
  5. public Task OwinHandler(IDictionary<string, object> environment)
  6. {
  7. string responseText = "Hello World via OWIN";
  8. byte[] responseBytes = Encoding.UTF8.GetBytes(responseText);
  9. // OWIN Environment Keys: http://owin.org/spec/spec/owin-1.0.0.html
  10. var requestMethod = (string) environment["owin.RequestMethod"];
  11. var requestScheme = (string) environment["owin.RequestScheme"];
  12. var requestHeaders = (IDictionary<string, string[]>)environment["owin.RequestHeaders"];
  13. var requestQueryString = (string) environment["owin.RequestQueryString"];
  14. var responseStream = (Stream)environment["owin.ResponseBody"];
  15. var responseHeaders = (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
  16. responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
  17. responseHeaders["Content-Type"] = new string[] { "text/plain" };
  18. return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length);
  19. }

Middleware

Run

  1. public void Configuration(IAppBuilder app)
  2. {
  3. app.Run(async context => await context.Response.WriteAsync("Hello World"));
  4. }

Uworzenie metody własnej warstwy pośredniej

  1. app.Use(async (context, next) =>
  2. {
  3. Trace.WriteLine(String.Format("request: {0} - {1}", context.Request.Method, context.Request.Path));
  4. await next.Invoke();
  5. Trace.WriteLine(String.Format("response: {0}", context.Response.StatusCode));
  6. });

Uworzenie klasy własnej warstwy pośredniej

Na przykładzie przekazywania formatu poprzez URL, np. http://localhost:5000/api/values?format=application/xml

RequestAcceptMiddleware.cs

  1. public class RequestAcceptMiddleware
  2. {
  3. private readonly RequestDelegate next;
  4. public RequestAcceptMiddleware(RequestDelegate next)
  5. {
  6. this.next = next;
  7. }
  8. public async Task InvokeAsync(HttpContext context)
  9. {
  10. var formatQuery = context.Request.Query["format"];
  11. if (!string.IsNullOrWhiteSpace(formatQuery))
  12. {
  13. context.Request.Headers.Remove("Accept");
  14. context.Request.Headers.Append("Accept", new string[] { formatQuery });
  15. }
  16. // Call the next delegate/middleware in the pipeline
  17. await next(context);
  18. }
  19. }

Startup.cs

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. app.UseMiddleware<RequestAcceptMiddleware>();
  4. }

Zastosowanie metody rozszerzającej

RequestAcceptMiddlewareExtensions.cs

  1. public static class RequestAcceptMiddlewareExtensions
  2. {
  3. public static IApplicationBuilder UseRequestAccept(
  4. this IApplicationBuilder builder)
  5. {
  6. return builder.UseMiddleware<RequestAcceptMiddleware>();
  7. }
  8. }

Startup.cs

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. app.UseRequestAccept();
  4. }

Mapowanie tras

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. app.Map("/dashboard", HandleMapTest1);
  4. app.Map("/sensors", node =>
  5. {
  6. node.Map("/temp", TempDelegate);
  7. node.Map("/humidity", HumidityDelegate);
  8. node.Map(string.Empty, SensorsDelegate);
  9. });
  10. }
  11. private void HumidityDelegate(IAppBuilder app)
  12. {
  13. app.Run(async context => await context.Response.WriteAsync("1024 hPa"));
  14. }
  15. private void TempDelegate(IAppBuilder app)
  16. {
  17. app.Run(async context => await context.Response.WriteAsync("Temp 23C"));
  18. }

Mapowanie warunkowe

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. app.MapWhen(context => context.Request.Headers.Get("Host").StartsWith("localhost"), LocalHostDelegate);
  4. }
  5. private void LocalHostDelegate(IAppBuilder app)
  6. {
  7. app.Run(async context => await context.Response.WriteAsync("localhost"));
  8. }

Mapowanie akcji

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. var rb = new RouteBuilder(app);
  4. rb.Routes.Add(new Route(new MyRouter(), "fib/{number:int}",
  5. app.ApplicationServices.GetService<IInlineConstraintResolver>()));
  6. rb.MapGet("", request => request.Response.WriteAsync("Hello World"));
  7. rb.MapGet("sensors", request => request.Response.WriteAsync("Sensors"));
  8. rb.MapGet("sensors/{id:int}", request => request.Response.WriteAsync($"Sensor id {request.GetRouteValue("id")}"));
  9. rb.MapPost("post", request => request.Response.WriteAsync("Created"));
  10. app.UseRouter(rb.Build());

Signal-R

Utworzenie koncetratora (huba)

CustomersHub.cs

  1. public class CustomersHub : Hub
  2. {
  3. public override Task OnConnectedAsync()
  4. {
  5. return base.OnConnectedAsync();
  6. }
  7. public Task CustomerAdded(Customer customer)
  8. {
  9. return this.Clients.Others.SendAsync("Added", customer);
  10. }
  11. public Task Ping(string message="Pong")
  12. {
  13. return this.Clients.Caller.SendAsync(message);
  14. }
  15. }

Rejestracja koncentratora

  1. public class Startup
  2. {
  3. public void ConfigureServices(IServiceCollection services)
  4. {
  5. services.AddSignalR();
  6. }
  7. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  8. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  9. {
  10. app.UseSignalR(routes => routes.MapHub<CustomersHub>("/hubs/customers"));
  11. if (env.IsDevelopment())
  12. {
  13. app.UseDeveloperExceptionPage();
  14. }
  15. app.Run(async (context) =>
  16. {
  17. await context.Response.WriteAsync("Hello World!");
  18. });
  19. }

Utworzenie nadawcy

  1. static async Task Main(string[] args)
  2. {
  3. const string url = "http://localhost:5000/hubs/customers";
  4. HubConnection connection = new HubConnectionBuilder()
  5. .WithUrl(url)
  6. .Build();
  7. connection.Closed += ex => Task.Run(() => System.Console.WriteLine($"ERROR {ex.Message}"));
  8. await connection.StartAsync();
  9. Customer customer = new Customer
  10. {
  11. FirstName = "Marcin",
  12. LastName = "Sulecki"
  13. };
  14. while (true)
  15. {
  16. await connection.SendAsync("CustomerAdded", customer);
  17. await Task.Delay(TimeSpan.FromSeconds(1));
  18. }

Utworzenie odbiorcy

  1. static async Task Main(string[] args)
  2. {
  3. const string url = "http://localhost:5000/hubs/customers";
  4. // dotnet add package Microsoft.AspNetCore.SignalR.Client
  5. HubConnection connection = new HubConnectionBuilder()
  6. .WithUrl(url)
  7. .Build();
  8. connection.Closed += ex => Task.Run(()=>System.Console.WriteLine($"ERROR {ex.Message}"));
  9. await connection.StartAsync();
  10. connection.On<Customer>("Added",
  11. customer => Console.WriteLine($"Added customer {customer.FirstName}"));
  12. }

Wstrzykiwanie huba

CustomersController.cs

  1. public class CustomersController : ControllerBase
  2. {
  3. private readonly IHubContext<CustomersHub> hubContext;
  4. public CustomersController(IHubContext<CustomersHub> hubContext)
  5. {
  6. this.hubContext = hubContext;
  7. }
  8. [HttpPost]
  9. public async Task<IActionResult> Post( Customer customer)
  10. {
  11. customersService.Add(customer);
  12. await hubContext.Clients.All.SendAsync("Added", customer);
  13. return CreatedAtRoute(new { Id = customer.Id }, customer);
  14. }
  15. }

Autentykacja

Program.cs

  1. static async Task Main(string[] args)
  2. {
  3. const string url = "http://localhost:5000/hubs/customers";
  4. var username = "your-username";
  5. var password = "your-password";
  6. var credentialBytes = Encoding.UTF8.GetBytes($"{username}:{password}");
  7. var credentials = Convert.ToBase64String(credentialBytes);
  8. string parameter = $"Basic {credentials}";
  9. HubConnection connection = new HubConnectionBuilder()
  10. .WithUrl(url, options => options.Headers.Add("Authorization", parameter))
  11. .Build();
  12. await connection.StartAsync();
  13. await connection.SendAsync("CustomerAdded", customer);
  14. }

Utworzenie silnie typowanego huba

CustomersHub.cs

  1. public interface ICustomersHub
  2. {
  3. Task Added(Customer customer);
  4. }
  5. public class CustomersHub : Hub<ICustomersHub>
  6. {
  7. public Task CustomerAdded(Customer customer)
  8. {
  9. return this.Clients.Others.Added(customer);
  10. }
  11. }

Wstrzykiwanie silnie typowanego huba

CustomersController.cs

  1. public class CustomersController : ControllerBase
  2. {
  3. private readonly IHubContext<CustomersHub, ICustomersHub> hubContext;
  4. public CustomersController(IHubContext<CustomersHub, ICustomersHub> hubContext)
  5. {
  6. this.hubContext = hubContext;
  7. }
  8. [HttpPost]
  9. public async Task<IActionResult> Post( Customer customer)
  10. {
  11. customersService.Add(customer);
  12. await hubContext.Clients.All.Added(customer);
  13. return CreatedAtRoute(new { Id = customer.Id }, customer);
  14. }
  15. }

Grupy

  1. public async Task AddToGroup(string groupName)
  2. {
  3. await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
  4. await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
  5. }
  6. public async Task RemoveFromGroup(string groupName)
  7. {
  8. await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
  9. await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has left the group {groupName}.");
  10. }

Testy jednostkowe

MSUnit

Utworzenie projektu

  1. dotnet new nunit

Przykładowa klasa

  1. public class Calculator
  2. {
  3. public int Add(int x, int y) => x + y;
  4. }

Test

  1. [TestClass]
  2. public class UnitTest1
  3. {
  4. [TestMethod]
  5. public void TestMethod1()
  6. {
  7. var calculator = new Calculator();
  8. var result = calculator.Add(2, 2);
  9. Assert.AreEqual(4, result);
  10. }
  11. }

xUnit

Utworzenie projektu

  1. dotnet new xunit

Przykładowa klasa

  1. public class Calculator
  2. {
  3. public int Add(int x, int y) => x + y;
  4. }

Fakt

  1. [Fact]
  2. public void Test1()
  3. {
  4. var calculator = new Calculator();
  5. int result = calculator.Add(2, 2);
  6. Assert.Equal(4, result);
  7. }

Teoria - inlinedata

  1. [Theory]
  2. [InlineData(1, 2, 3)]
  3. [InlineData(-4, -6, -10)]
  4. [InlineData(-2, 2, 0)]
  5. [InlineData(int.MinValue, -1, int.MaxValue)]
  6. public void CanAddTheory(int value1, int value2, int expected)
  7. {
  8. var calculator = new Calculator();
  9. var result = calculator.Add(value1, value2);
  10. Assert.Equal(expected, result);
  11. }

Teoria - classdata

  1. public class CalculatorTestData : TheoryData<int, int, int>
  2. {
  3. public CalculatorTestData()
  4. {
  5. Add(1, 2, 3);
  6. Add(-4, -6, -10);
  7. Add(-2, 2, 0);
  8. Add(int.MinValue, -1, int.MaxValue);
  9. }
  10. }
  11. [Theory]
  12. [ClassData(typeof(CalculatorTestData))]
  13. public void CanAdd(int value1, int value2, int expected)
  14. {
  15. var calculator = new Calculator();
  16. var result = calculator.Add(value1, value2);
  17. Assert.Equal(expected, result);
  18. }

Teoria - memberdata

  1. public static IEnumerable<object[]> Data =>
  2. new List<object[]>
  3. {
  4. new object[] { 1, 2, 3 },
  5. new object[] { -4, -6, -10 },
  6. new object[] { -2, 2, 0 },
  7. new object[] { int.MinValue, -1, int.MaxValue },
  8. };
  9. [Theory]
  10. [MemberData(nameof(Data))]
  11. public void CanAddTheoryMemberDataProperty(int value1, int value2, int expected)
  12. {
  13. var calculator = new Calculator();
  14. var result = calculator.Add(value1, value2);
  15. Assert.Equal(expected, result);
  16. }

FluentAssertions

Kontrola kondycji

Rejestrowanie kondycji

Kondycja SQL Server

  1. dotnet add package AspNetCore.HealthChecks.SqlServer

Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddHealthChecksUI()
  4. .AddSqlServer(Configuration.GetConnectionStrings("MyConnection");
  5. }

Kondycja DbContext

  1. dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore

Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
  4. services.AddHealthChecks()
  5. .AddDbContextCheck<AppDbContext>();
  6. }

Utworzenie własnej kontroli kondycji

RandomHealthCheck.cs

  1. public class RandomHealthCheck : IHealthCheck
  2. {
  3. public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
  4. {
  5. if (DateTime.UtcNow.Minute % 2 == 0)
  6. {
  7. return Task.FromResult(HealthCheckResult.Healthy());
  8. }
  9. return Task.FromResult(HealthCheckResult.Unhealthy(description: "failed"));
  10. }
  11. }

Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddHealthChecks()
  4. .AddCheck<RandomHealthCheck>("random");
  5. }

Dashboard

Instalacja

  1. dotnet add package AspNetCore.HealthChecks.UI

Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddHealthChecksUI();
  4. }
  5. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  6. {
  7. app.UseHealthChecks("/health", new HealthCheckOptions()
  8. {
  9. Predicate = _ => true,
  10. ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
  11. });
  12. }

appsettings.json

  1. "HealthChecks-UI": {
  2. "HealthChecks": [
  3. {
  4. "Name": "Http and UI on single project",
  5. "Uri": "http://localhost:5000/health"
  6. }
  7. ],
  8. "Webhooks": [],
  9. "EvaluationTimeOnSeconds": 10,
  10. "MinimumSecondsBetweenFailureNotifications": 60
  11. }

Wskazówka: Przejdź na http://localhost:5000/healthchecks-ui aby zobaczyc panel

Generowanie dokumentacji

W formacie Swagger/OpenApi

Instalacja

  1. dotnet add TodoApi.csproj package Swashbuckle.AspNetCore

Konfiguracja

Plik Startup.cs

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services
  4. .AddSwaggerGen(c => c.SwaggerDoc("v1", new Info { Title = "My Api", Version = "1.0" }));
  5. }
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. app.UseSwagger();
  4. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
  5. }

Docker

  • Uruchomienie pierwszego kontenera

    1. docker run ubuntu /bin/echo 'Hello world'
  • Uruchomienie w trybie interaktywnym

    1. docker run -i -t --rm ubuntu /bin/bash

Przydatne komendy

  • docker images - lista wszystkich obrazów na twojej maszynie
  • docker pull <image> - pobranie obrazu
  • docker run <image> - uruchomienie obrazu (pobiera jeśli nie ma)
  • docker ps - lista wszystkich uruchomionych kontenerów na twojej maszynie
  • docker ps -a - lista wszystkich przyłączonych ale nie uruchomionych kontenerów
  • docker start <containter_name> - uruchomienie kontenera wg nazwy
  • docker stop <containter_name> - zatrzymanie kontenera wg nazwy

Konteneryzacja aplikacji .NET Core

  • Utwórz plik Dockerfile
  1. FROM microsoft/dotnet:2.0-sdk
  2. WORKDIR /app
  3. # copy csproj and restore as distinct layers
  4. COPY *.csproj ./
  5. RUN dotnet restore
  6. # copy and build everything else
  7. COPY . ./
  8. RUN dotnet publish -c Release -o out
  9. ENTRYPOINT ["dotnet", "out/Hello.dll"]

ngrok

  • Uruchomienie
  1. ngrok http 5000
  • Interfejs webowy
  1. http://127.0.0.1:4040
  • API
  1. http://127.0.0.1:4040/api