Asp.Net Core Api接口实现CURD并通过Ajax发送请求进行访问

前言,课程作业,使用前后端分离的思想设计一个web应用,我采用了asp.net core web api(.net 5)实现对一个SQLite数据库的增删改查的api接口,并使用ajax进行访问。

Gitee仓库地址

最终效果

在这里插入图片描述

一,通过EF Core对现有的数据库进行反向工程,生成实体类和数据库上下文。

  • 1,反向工程请查看微软官方文档
    反向工程 EF Core
  • 2, 数据库表和数据库生成的实体类
    在这里插入图片描述
using System;
using System.Collections.Generic;

#nullable disable

namespace SoftwareProject.Models
{
    public partial class Author
    {
        public string AuId { get; set; }
        public string AuLname { get; set; }
        public string AuFname { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public long Contract { get; set; }
    }
}

  • 3,数据库上下文
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using SoftwareProject.Models;

#nullable disable

namespace SoftwareProject.Data
{
    public partial class PubsContext : DbContext
    {

        public PubsContext(DbContextOptions<PubsContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Author> Authors { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Author>(entity =>
            {
                entity.HasKey(e => e.AuId);

                entity.ToTable("authors");

                entity.Property(e => e.AuId)
                    .HasColumnType("VARCHAR(11)")
                    .HasColumnName("au_id");

                entity.Property(e => e.Address)
                    .HasColumnType("varchar(40)")
                    .HasColumnName("address");

                entity.Property(e => e.AuFname)
                    .IsRequired()
                    .HasColumnType("varchar(20)")
                    .HasColumnName("au_fname");

                entity.Property(e => e.AuLname)
                    .IsRequired()
                    .HasColumnType("varchar(40)")
                    .HasColumnName("au_lname");

                entity.Property(e => e.City)
                    .HasColumnType("varchar(20)")
                    .HasColumnName("city");

                entity.Property(e => e.Contract)
                    .HasColumnType("INT")
                    .HasColumnName("contract");

                entity.Property(e => e.Phone)
                    .IsRequired()
                    .HasColumnType("char(12)")
                    .HasColumnName("phone");

                entity.Property(e => e.State)
                    .HasColumnType("char(2)")
                    .HasColumnName("state");

                entity.Property(e => e.Zip)
                    .HasColumnType("char(5)")
                    .HasColumnName("zip");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

  • 4,Startup.cs

这个地方要注意一下,因为我ajax的网页是在Tomcat服务器上,请求地址为:“http://localhost:8080”
而后端API的地址为:https://localhost:5001,故存在跨域请求的问题,所以要配置跨域:
官方文档地址为:(CORS) 启用跨域请求 ASP.NET Core

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using SoftwareProject.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SoftwareProject
{
    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.AddCors(options =>
            {
                options.AddDefaultPolicy(
                	// 允许使用任何请求方式和任何请求头进行请求API 
                    build =>
                    {
                        build.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader();
                    }
                    );
            });

            services.AddControllers();

            services.AddDbContext<PubsContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("PubsContext")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            // 配置跨站请求
            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

  • 5,appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
  	// 数据库连接字符串
    "PubsContext": "Filename=Data\\pubs.db"
  }
}


二,通过使用微软官方的脚手架生成实体类Author增删改查的API接口

官方文档:教程:使用 ASP.NET Core 创建 Web API
在这里插入图片描述

生成的api接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SoftwareProject.Data;
using SoftwareProject.Models;

namespace SoftwareProject.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorsController : ControllerBase
    {
        private readonly PubsContext _context;

        public AuthorsController(PubsContext context)
        {
            _context = context;
        }

        // GET: api/Authors
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Author>>> GetAuthors()
        {
            return await _context.Authors.ToListAsync();
        }

        // GET: api/Authors/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Author>> GetAuthor(string id)
        {
            var author = await _context.Authors.FindAsync(id);

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

            return author;
        }




        // PUT: api/Authors/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutAuthor(string id, Author author)
        {
            if (id != author.AuId)
            {
                return BadRequest();
            }

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

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

            return NoContent();
        }

        // POST: api/Authors
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Author>> PostAuthor(Author author)
        {
            _context.Authors.Add(author);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (AuthorExists(author.AuId))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtAction("GetAuthor", new { id = author.AuId }, author);
        }

        // DELETE: api/Authors/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAuthor(string id)
        {
            var author = await _context.Authors.FindAsync(id);
            if (author == null)
            {
                return NotFound();
            }

            _context.Authors.Remove(author);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool AuthorExists(string id)
        {
            return _context.Authors.Any(e => e.AuId == id);
        }
    }
}

三,Ajax请求Web Api

使用了Bootstrap4前端框架和Tomcat作为测试服务器
注意:当提交json数据时,一定要使用JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串,不然会报错。
项目目录结构
只有一个index.html页面,通过ajax进行异步请求,完成CRUD服务。

<!DOCTYPE html>
<html lang="en">

<head>

    <head>
        <!-- 必须的 meta 标签 -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap 的 CSS 文件 -->
        <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <style>
            .table tbody tr td {
                vertical-align: middle;
            }
        </style>

        <title>Hello, world!</title>
    </head>


</head>





<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-8">
                <h3 class="text-center">数据列表</h3>
                <table id="author" class="table">
                    <thead>
                        <tr class="text-center">
                            <td>Id</td>
                            <td>AuLname</td>
                            <td>AuFname</td>
                            <td>Phone</td>
                            <td>Address</td>
                            <td>City</td>
                            <td>State</td>
                            <td>Zip</td>
                            <td>Contract</td>
                            <td>删除操作</td>
                        </tr>
                    </thead>
                </table>
            </div>
            <div class="col-4">
                
                <h3 class="text-center">增加&&查询</h3>
                <div class="alert alert-danger" role="alert">
                    在添加之前,请通过在Search输入框中输入auId进行查询,查询结果将填充表单,修改id即可增加<br/>
                    在修改之前,请通过在Search输入框中输入auId,查询会自动填充表单,然后点击修改按钮
                  </div>
                <!-- 添加查询 -->
                <div class="form-group row">
                    <label for="search" class="col-sm-2 col-form-label">search</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" id="search" name="search">
                    </div>
                    <div class="col-sm-2">
                        <input type="button" value="查询" class="btn btn-primary" id="searchBtn" />
                    </div>
                </div>
                <form id="form">
                    <div class="form-group row">
                        <label for="auId" class="col-sm-2 col-form-label">auId</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="auId" name="auId" value="341-22-1782">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="auLname" class="col-sm-2 col-form-label">auLname</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="auLname" name="auLname" value="猪猪">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="auFname" class="col-sm-2 col-form-label">auFname</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="auFname" name="auFname" value="憨憨">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="phone" class="col-sm-2 col-form-label">phone</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="phone" name="phone" value="15977744497">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="address" class="col-sm-2 col-form-label">address</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="address" name="address" value="北道">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="city" class="col-sm-2 col-form-label">city</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="city" name="city" value="天水">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="state" class="col-sm-2 col-form-label">state</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="state" name="state" value="甘肃">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="zip" class="col-sm-2 col-form-label">zip</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="zip" name="zip" value="741037">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="contract" class="col-sm-2 col-form-label">contract</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="contract" name="contract" value="5">
                        </div>
                    </div>
                    <input type="button" value="添加" onclick="addAuthor()" class="btn btn-success" />
                    <input type="button" value="修改" id="changeAuthor" class="btn btn-info" />
                </form>

                
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script>
        function addAuthor() {
            var authorData = $('#form').serializeArray()
            var authorJson = {}
            for (var i = 0; i < authorData.length; i++) {
                authorJson[authorData[i]['name']] = authorData[i]['value']

            }
            // console.log(JSON.stringify(authorJson))
            $.ajax({ //几个参数需要注意一下
                url: "https://localhost:5001/api/authors",
                type: "post",
                datatype: "json",
                contentType: "application/json;charsetset=UTF-8",
                data: JSON.stringify(authorJson), // 一定要写成这样不然会报400错误
                success: function (result) {
                    alert("添加成功!!!")
                },
                error: function (err) {
                    alert("添加失败:" + err.message +
                        "状态码:" + err.status)
                }
            })
        }

        function deleteById(auId) {
            if (confirm("确定删除吗???")) {
                $.ajax({
                    url: "https://localhost:5001/api/authors/" + auId,
                    type: "Delete",
                    success: function (data) {
                        $("#" + auId).remove()
                        alert("删除成功");
                    },
                    error: function (err) {
                        alert("删除失败:" + err.message +
                            "状态码:" + err.status)
                    }
                })
            }
        }
        // 返回所有数据并生成表格
        $.get("https://localhost:5001/api/authors", function (data) {
            // console.log(data)
            var authorTable = $('#author');
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                authorTable.append('<tbody><tr class="text-center" id="' + item.auId + '"> ' +
                    '<td>' + item.auId + '</td>' +
                    '<td>' + item.auLname + '</td>' +
                    '<td>' + item.auFname + '</td>' +
                    '<td>' + item.phone + '</td>' +
                    '<td>' + item.address + '</td>' +
                    '<td>' + item.city + '</td>' +
                    '<td>' + item.state + '</td>' +
                    '<td>' + item.zip + '</td>' +
                    '<td>' + item.contract + '</td>' +
                    '<td><button class="btn btn-danger btn-sm" οnclick="deleteById(\'' + item.auId +
                    '\')">删除</button></td>' +
                    '</tr></tbody>')
            }
        });
        $(function () {
            // 返回所有authors
            $('#getAll').click(function () {
                $.get("https://localhost:5001/api/authors", function (data) {
                    for (var i = 0; i < data.length; i++) {
                        alert(data[i].auId + ":" + data[i].city)
                    }
                });
            });

            // 返回一个特定auId的同学
            $('#searchBtn').click(function () {
                var auId = $("#search").val()
                // alert(auId)
                $.ajax({
                    url: "https://localhost:5001/api/authors/" + auId,
                    type: "GET",
                    success: function (data) {
                        // console.log(data);
                        $("#auId").val(data['auId']);
                        $("#auLname").val(data['auLname']);
                        $("#auFname").val(data['auFname']);
                        $("#phone").val(data['phone']);
                        $("#address").val(data['address']);
                        $("#city").val(data['city']);
                        $("#state").val(data['state']);
                        $("#zip").val(data['zip']);
                        $("#contract").val(data['contract']);

                        alert("查询成功,已经显示到了添加文本框中")
                    },
                    error: function (err) {
                        alert("查询失败:" + err.message +
                            "状态码:" + err.status)
                    }

                });
            })

            $('#changeAuthor').click(function () {
                var auId = $("#search").val()
                var auId2 = $("#auId").val()
                if (auId == auId2) { // 如果查询文本框中的input auId值和添加文本框input中的auId相同。则认为可以修改
                    authorJson = {
                        "auId": $("#auId").val(),
                        "auLname": $("#auLname").val(),
                        "auFname": $("#auFname").val(),
                        "phone": $("#phone").val(),
                        "address": $("#address").val(),
                        "city": $("#city").val(),
                        "state": $("#state").val(),
                        "zip": $("#zip").val(),
                        "contract": $("#contract").val(),
                    }

                    $.ajax({ //几个参数需要注意一下

                        url: "https://localhost:5001/api/authors/" + auId,
                        type: "put",
                        datatype: "json",
                        contentType: "application/json;charsetset=UTF-8",
                        data: JSON.stringify(authorJson), // 一定要写成这样不然会报400错误
                        success: function (result) {

                            alert("修改成功!!!")

                        },
                        error: function (err) {
                            alert("修改失败:" + err.message +
                                "状态码:" + err.status)
                        }
                    })
                    console.log(authorJson)
                } else {
                    alert("查询框中ID和添加框中ID不一致,请重新填写")
                }

            })

        })
    </script>
</body>

</html>
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值