少说话多写代码之.net core——001:建一个api

栏目: ASP.NET · 发布时间: 7年前

内容简介:2、添加模型类3、添加数据上下文4、注册数据上下文

一、.net core环境准备

直接装visualstudio 2017,具体安装方法,自行下载安装即可。

二、.net core使用

用.net core编写一个webapi。

具体过程如下,

1、新建工程

少说话多写代码之.net core——001:建一个api

2、添加模型类

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

3、添加数据上下文

  public class MyContext: DbContext
    {
        public MyContext(DbContextOptions<MyContext> options)
            : base(options)
        {
        }
        public DbSet<MyItem> MyItems { get; set; }
    }

4、注册数据上下文

 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<MyContext>(opt =>
               opt.UseInMemoryDatabase("TodoList"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }

5、添加控制器及相关方法

添加get,post,delete等方法

 public class MyController : Controller
    {
        private readonly MyContext _context;

        public MyController(MyContext context)
        {
            _context = context;

            if (_context.MyItems.Count() == 0)
            {
                _context.MyItems.Add(new MyItem {Id=99, Name = "我的自定义的控制器_99 "+DateTime.Now.ToLocalTime() });
                _context.MyItems.Add(new MyItem {Id =100, Name = "我的自定义的控制器_100 " + DateTime.Now.ToLocalTime() });
                _context.SaveChanges();
            }
        }

        // GET: api/Todo
        [HttpGet]
        public async Task<ActionResult<IEnumerable<MyItem>>> GetMyItems()
        {
            return await _context.MyItems.ToListAsync();
        }

        // GET: api/Todo/99
        [HttpGet("{id}")]
        public async Task<ActionResult<MyItem>> GetMyItem(long id)
        {
            var todoItem = await _context.MyItems.FindAsync(id);

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

            return todoItem;
        }
        // POST: api/Todo
        [HttpPost]
        public async Task<ActionResult<MyItem>> PostMyItem(MyItem item)
        {
            _context.MyItems.Add(item);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetMyItem", new { id = item.Id , Name = item.Name}, item);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> PutMyItem(long id, MyItem item)
        {
            if (id != item.Id)
            {
                return BadRequest();
            }
            _context.Entry(item).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return NoContent();
        }

        // DELETE: api/Todo/101
        [HttpDelete("{id}")]
        public async Task<ActionResult<MyItem>> DeleteMyItem(long id)
        {
            var todoItem = await _context.MyItems.FindAsync(id);
            if (todoItem == null)
            {
                return NotFound();
            }

            _context.MyItems.Remove(todoItem);
            await _context.SaveChangesAsync();

            return todoItem;
        }
    }

6、设置路由

在刚新加的控制器上新增路由,比如

    [Route("api/My")]
    [ApiController]
    public class MyController : Controller

同时在launchSettings.json中设置,访问默认路径,比如

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:50228",
      "sslPort": 44364
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/My",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyToDoApi": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/My",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

7、测试

在工程上启用调试,本文使用postman进行测试。

启用调试后,在浏览器页面中地址为:https://localhost:44364/api/My,显示内容如下,

[{"id":99,"name":"我的自定义的控制器_99 2019/1/13 23:26:24","isComplete":false},{"id":100,"name":"我的自定义的控制器_100 2019/1/13 23:26:24","isComplete":false}]

7.1、测试get方法

GetMyItems调用如下,

少说话多写代码之.net core——001:建一个api

GetMyItem调用如下,

少说话多写代码之.net core——001:建一个api

7.2、测试post方法

PostMyItem调用如下,

少说话多写代码之.net core——001:建一个api

调用后,在浏览器页面验证如下

少说话多写代码之.net core——001:建一个api

7.3、测试put方法

PutMyItem调用如下

少说话多写代码之.net core——001:建一个api

浏览器中验证,

少说话多写代码之.net core——001:建一个api

7.4、测试delete方法

DeleteMyItem调用如下,

少说话多写代码之.net core——001:建一个api

浏览器中验证,

少说话多写代码之.net core——001:建一个api

工程文件下载: https://download.csdn.net/upload/10914869


以上所述就是小编给大家介绍的《少说话多写代码之.net core——001:建一个api》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Ruby

Programming Ruby

Dave Thomas、Chad Fowler、Andy Hunt / Pragmatic Bookshelf / 2004-10-8 / USD 44.95

Ruby is an increasingly popular, fully object-oriented dynamic programming language, hailed by many practitioners as the finest and most useful language available today. When Ruby first burst onto the......一起来看看 《Programming Ruby》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具