少說話多寫程式碼之.net core——001:建一個api
阿新 • • 發佈:2019-01-14
一、.net core環境準備
直接裝visualstudio 2017,具體安裝方法,自行下載安裝即可。
二、.net core使用
用.net core編寫一個webapi。
具體過程如下,
1、新建工程
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呼叫如下,
GetMyItem呼叫如下,
7.2、測試post方法
PostMyItem呼叫如下,
呼叫後,在瀏覽器頁面驗證如下
7.3、測試put方法
PutMyItem呼叫如下
瀏覽器中驗證,
7.4、測試delete方法
DeleteMyItem呼叫如下,
瀏覽器中驗證,