白季飞龙的个人主页

dotNet大杂烩

1. Hello World

using System;

namespace ConsoleApplication1
{
    internal static class App
    {
        public static void Main()
        {
            Console.WriteLine("Hello World");
        }
    }
}

2. Hello WinForm

using System;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    internal class Program : Form
    {
        public static void Main(string[] args)
        {
            Application.Run(new Program());
        }

        public Program()
        {
            Button button = new Button();
            button.Text = "Click Me!";
            button.Click += Button_Click;
            Controls.Add(button);
        }

        private void Button_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Clicked");
        }
    }
}

3. Hello Web

using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace HelloWeb
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            WebHost.CreateDefaultBuilder(args)
                .Configure(app => { app.Run(async it => await it.Response.WriteAsync("Hello World!")); })
                .Build().Run();
        }
    }
}

4. MVC

using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace HelloWeb
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            WebHost.CreateDefaultBuilder(args)
                .ConfigureServices(services => { services.AddMvc(); })
                .Configure(app => { app.UseMvc(); })
                .Build().Run();
        }
    }

    public class HomeController : ControllerBase
    {
        [Route("/")]
        public ActionResult<string> Get()
        {
            return "Hello World!";
        }

        [Route("/help")]
        public ActionResult<string> Help()
        {
            return "Help";
        }
    }
}

5. Restful API

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace HelloWeb
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    services.AddMvc();
                    services.AddDbContext<TodoContext>(opt => { opt.UseInMemoryDatabase("Todo"); });
                })
                .Configure(app =>
                {
                    app.UseMvc();
                    app.UseDeveloperExceptionPage();
                })
                .Build().Run();
        }
    }

    [Route("[controller]")]
    public class TodosController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodosController(TodoContext context)
        {
            _context = context;
            if (_context.Todos.Any()) return;
            _context.Todos.Add(new Todo {Name = "Item1"});
            _context.SaveChanges();
        }

        [HttpGet]
        public List<Todo> GetAll()
        {
            return _context.Todos.ToList();
        }

        [HttpGet("{id}", Name = "GetTodo")]
        public IActionResult GetById(long id)
        {
            var item = _context.Todos.Find(id);
            if (item == null)
            {
                return NotFound();
            }

            return Ok(item);
        }

        [HttpPost]
        public IActionResult Create([FromBody] Todo todo)
        {
            if (todo == null)
            {
                return BadRequest();
            }

            _context.Todos.Add(todo);
            _context.SaveChanges();

            return CreatedAtRoute("GetTodo", new {id = todo.Id}, todo);
        }

        [HttpPut("{id}")]
        public IActionResult Update(long id, [FromBody] Todo item)
        {
            if (item == null || item.Id != id)
            {
                return BadRequest();
            }

            var todo = _context.Todos.Find(id);
            if (todo == null)
            {
                return NotFound();
            }

            todo.IsComplete = item.IsComplete;
            todo.Name = item.Name;

            _context.Todos.Update(todo);
            _context.SaveChanges();
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(long id)
        {
            var todo = _context.Todos.Find(id);
            if (todo == null)
            {
                return NotFound();
            }

            _context.Todos.Remove(todo);
            _context.SaveChanges();
            return NoContent();
        }
    }

    public class Todo
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }

    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<Todo> Todos { get; set; }
    }
}

漫漫路,莫论逍遥;潜心修,只为悟道