数据库
首页 > 数据库> > webapi+efcore+mysql+iis

webapi+efcore+mysql+iis

作者:互联网

1.创建WebApiDemo

 

 

2.创建Person类

public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

    }

 

3.添加context上下文

 public class ModelContext: DbContext
    {
        public ModelContext()
        {

        }

        public ModelContext(DbContextOptions<ModelContext> options) : base(options)
        {

        }

        public DbSet<Person> Persons { get; set; }
    }

对应的数据库

 

 

4.添加连接字符串

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "MySQLConnection": "server=10.53.1.65;port=3306;uid=root;pwd=hfwhjkhf;database=dbtest"
  },
  "AllowedHosts": "*"
}

6.服务注入

builder.Services.AddDbContext<ModelContext>(opt =>
{
    string connectingString = builder.Configuration.GetConnectionString("MySQLConnection");
    var serverVersion = Microsoft.EntityFrameworkCore.ServerVersion.AutoDetect(connectingString);
    opt.UseMySql(connectingString, serverVersion);
});

 

7.创建控制器

 

 

 

 

 如果报错后,再次点击添加即可。

8.生成控制器代码

[Route("api/[controller]")]
    [ApiController]
    public class PeopleController : ControllerBase
    {
        private readonly ModelContext _context;

        public PeopleController(ModelContext context)
        {
            _context = context;
        }

        // GET: api/People
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Person>>> GetPersons()
        {
          if (_context.Persons == null)
          {
              return NotFound();
          }
            return await _context.Persons.ToListAsync();
        }

        // GET: api/People/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Person>> GetPerson(int id)
        {
          if (_context.Persons == null)
          {
              return NotFound();
          }
            var person = await _context.Persons.FindAsync(id);

            if (person == null)
            {
                return NotFound();
            }

            return person;
        }

        // PUT: api/People/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutPerson(int id, Person person)
        {
            if (id != person.Id)
            {
                return BadRequest();
            }

            _context.Entry(person).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PersonExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/People
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Person>> PostPerson(Person person)
        {
          if (_context.Persons == null)
          {
              return Problem("Entity set 'ModelContext.Persons'  is null.");
          }
            _context.Persons.Add(person);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetPerson", new { id = person.Id }, person);
        }

        // DELETE: api/People/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePerson(int id)
        {
            if (_context.Persons == null)
            {
                return NotFound();
            }
            var person = await _context.Persons.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }

            _context.Persons.Remove(person);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool PersonExists(int id)
        {
            return (_context.Persons?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }

9.swagger测试

10.iss部署

参考(29条消息) 将WebAPI部署在IIS上_斯 钦的博客-CSDN博客_webapi部署到iis

 

标签:webapi,return,efcore,iis,Persons,id,person,context,public
来源: https://www.cnblogs.com/HRDK-CADeveloper/p/16305852.html