From f92a08fcd9c0a1104e6c46c0bede4f97d5e01f56 Mon Sep 17 00:00:00 2001 From: Cephas Lin Date: Tue, 28 Apr 2020 17:13:46 +0200 Subject: [PATCH] upgrade to core 3.1 --- Controllers/TodoController.cs | 116 +++++++++++++++++--------------- Controllers/TodoController2.cs | 28 -------- Controllers/ValuesController.cs | 41 ----------- Models/TodoContext.cs | 3 +- Program.cs | 21 +++--- Properties/launchSettings.json | 16 +++++ Startup.cs | 49 +++++++++++--- TodoApi.csproj | 21 +++--- appsettings.Development.json | 7 +- appsettings.json | 10 +-- 10 files changed, 150 insertions(+), 162 deletions(-) delete mode 100644 Controllers/TodoController2.cs delete mode 100644 Controllers/ValuesController.cs create mode 100644 Properties/launchSettings.json diff --git a/Controllers/TodoController.cs b/Controllers/TodoController.cs index 6a568c55..aad8137b 100644 --- a/Controllers/TodoController.cs +++ b/Controllers/TodoController.cs @@ -1,20 +1,21 @@ -using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; -using TodoApi.Models; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.EntityFrameworkCore; +using Newtonsoft.Json; +using System.Collections.Generic; using System.Linq; using System.Net.Http; -using Newtonsoft.Json; -using Microsoft.AspNetCore.Mvc.Filters; using System.Net.Http.Headers; +using System.Threading.Tasks; +using TodoApi.Models; -#region TodoController namespace TodoApi.Controllers { - [Route("api/[controller]")] + [Route("api/[controller]")] + [ApiController] public class TodoController : Controller { private readonly TodoContext _context; - #endregion public TodoController(TodoContext context) { @@ -27,81 +28,90 @@ public TodoController(TodoContext context) } } - #region snippet_GetAll + // GET: api/Todo [HttpGet] - public IEnumerable GetAll() + public async Task>> GetTodoItem() { - return _context.TodoItems.ToList(); + return await _context.TodoItems.ToListAsync(); } - #region snippet_GetByID - [HttpGet("{id}", Name = "GetTodo")] - public IActionResult GetById(long id) + // GET: api/Todo/5 + [HttpGet("{id}")] + public async Task> GetTodoItem(long id) { - var item = _context.TodoItems.FirstOrDefault(t => t.Id == id); - if (item == null) + var todoItem = await _context.TodoItems.FindAsync(id); + + if (todoItem == null) { return NotFound(); } - return new ObjectResult(item); - } - #endregion - #endregion - #region snippet_Create - [HttpPost] - public IActionResult Create([FromBody] TodoItem item) - { - if (item == null) - { - return BadRequest(); - } - - _context.TodoItems.Add(item); - _context.SaveChanges(); - return CreatedAtRoute("GetTodo", new { id = item.Id }, item); + return todoItem; } - #endregion - #region snippet_Update + // PUT: api/Todo/5 + // To protect from overposting attacks, please enable the specific properties you want to bind to, for + // more details see https://aka.ms/RazorPagesCRUD. [HttpPut("{id}")] - public IActionResult Update(long id, [FromBody] TodoItem item) + public async Task PutTodoItem(long id, TodoItem todoItem) { - if (item == null || item.Id != id) + if (id != todoItem.Id) { return BadRequest(); } - var todo = _context.TodoItems.FirstOrDefault(t => t.Id == id); - if (todo == null) + _context.Entry(todoItem).State = EntityState.Modified; + + try { - return NotFound(); + await _context.SaveChangesAsync(); + } + catch (DbUpdateConcurrencyException) + { + if (!TodoItemExists(id)) + { + return NotFound(); + } + else + { + throw; + } } - todo.IsComplete = item.IsComplete; - todo.Name = item.Name; + return NoContent(); + } - _context.TodoItems.Update(todo); - _context.SaveChanges(); - return new NoContentResult(); + // POST: api/Todo + // To protect from overposting attacks, please enable the specific properties you want to bind to, for + // more details see https://aka.ms/RazorPagesCRUD. + [HttpPost] + public async Task> PostTodoItem(TodoItem todoItem) + { + _context.TodoItems.Add(todoItem); + await _context.SaveChangesAsync(); + + return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem); } - #endregion - #region snippet_Delete + // DELETE: api/Todo/5 [HttpDelete("{id}")] - public IActionResult Delete(long id) + public async Task> DeleteTodoItem(long id) { - var todo = _context.TodoItems.FirstOrDefault(t => t.Id == id); - if (todo == null) + var todoItem = await _context.TodoItems.FindAsync(id); + if (todoItem == null) { return NotFound(); } - _context.TodoItems.Remove(todo); - _context.SaveChanges(); - return new NoContentResult(); + _context.TodoItems.Remove(todoItem); + await _context.SaveChangesAsync(); + + return todoItem; + } + + private bool TodoItemExists(long id) + { + return _context.TodoItems.Any(e => e.Id == id); } - #endregion } } - diff --git a/Controllers/TodoController2.cs b/Controllers/TodoController2.cs deleted file mode 100644 index 19294e38..00000000 --- a/Controllers/TodoController2.cs +++ /dev/null @@ -1,28 +0,0 @@ -#if NEVER -#region snippet_todo1 -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; -using TodoApi.Models; -using System.Linq; - -namespace TodoApi.Controllers -{ - [Route("api/[controller]")] - public class TodoController : Controller - { - private readonly TodoContext _context; - - public TodoController(TodoContext context) - { - _context = context; - - if (_context.TodoItems.Count() == 0) - { - _context.TodoItems.Add(new TodoItem { Name = "Item1" }); - _context.SaveChanges(); - } - } - } -} -#endregion -#endif \ No newline at end of file diff --git a/Controllers/ValuesController.cs b/Controllers/ValuesController.cs deleted file mode 100644 index 15831dae..00000000 --- a/Controllers/ValuesController.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; - -namespace TodoApi.Controllers -{ - [Route("api/[controller]")] - public class ValuesController : Controller - { - // GET api/values - [HttpGet] - public IEnumerable Get() - { - return new string[] { "value1", "value2" }; - } - - // GET api/values/5 - [HttpGet("{id}")] - public string Get(int id) - { - return "value"; - } - - // POST api/values - [HttpPost] - public void Post([FromBody]string value) - { - } - - // PUT api/values/5 - [HttpPut("{id}")] - public void Put(int id, [FromBody]string value) - { - } - - // DELETE api/values/5 - [HttpDelete("{id}")] - public void Delete(int id) - { - } - } -} diff --git a/Models/TodoContext.cs b/Models/TodoContext.cs index 5ddaa6d4..de24b36a 100644 --- a/Models/TodoContext.cs +++ b/Models/TodoContext.cs @@ -4,12 +4,11 @@ namespace TodoApi.Models { public class TodoContext : DbContext { - public TodoContext(DbContextOptions options) + public TodoContext (DbContextOptions options) : base(options) { } public DbSet TodoItems { get; set; } - } } diff --git a/Program.cs b/Program.cs index 737da22f..70690c2a 100644 --- a/Program.cs +++ b/Program.cs @@ -1,6 +1,5 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using System.IO; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace TodoApi { @@ -8,14 +7,14 @@ public class Program { public static void Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() - .Build(); - - host.Run(); + CreateHostBuilder(args).Build().Run(); } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); } } diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 00000000..ae124698 --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,16 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true + }, + "profiles": { + "TodoApi": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:5000" + } + } +} \ No newline at end of file diff --git a/Startup.cs b/Startup.cs index cb0fa576..aeb859af 100644 --- a/Startup.cs +++ b/Startup.cs @@ -1,40 +1,69 @@ using Microsoft.AspNetCore.Builder; -using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; using TodoApi.Models; -using Swashbuckle.AspNetCore.Swagger; namespace TodoApi { public class Startup - { + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList")); - services.AddMvc(); + services.AddControllers(); - // Register the Swagger generator, defining one or more Swagger documents + // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { - c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); + c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); + + services.AddDbContext(options => options.UseInMemoryDatabase("TodoList")); } - public void Configure(IApplicationBuilder app) + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); - // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. + // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), + // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + //app.UseHttpsRedirection(); + app.UseDefaultFiles(); + app.UseStaticFiles(); - app.UseMvc(); + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); } } } diff --git a/TodoApi.csproj b/TodoApi.csproj index fa56a4ee..4696ca57 100644 --- a/TodoApi.csproj +++ b/TodoApi.csproj @@ -1,17 +1,20 @@ - + - netcoreapp2.0 + netcoreapp3.1 - - - - - - + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + - diff --git a/appsettings.Development.json b/appsettings.Development.json index fa8ce71a..c9294ca4 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -1,10 +1,9 @@ { "Logging": { - "IncludeScopes": false, "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" } } } diff --git a/appsettings.json b/appsettings.json index 5fff67ba..84563e54 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,8 +1,10 @@ { "Logging": { - "IncludeScopes": false, "LogLevel": { - "Default": "Warning" + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" } - } -} + }, + "AllowedHosts": "*" +} \ No newline at end of file