using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace WebAPIForAndroid.Controllers { //[Route("api/[controller]")] //默认的路由规则 //url由原来的http://localhost:59640/api/StuInFors 变成:http://localhost:59640/api/StuInFors/post/ [Route("api/[controller]/[action]")]//自定义路由规则(必须指定action) [ApiController] public class StuInForsController : ControllerBase { // GET api/StuInFors [HttpGet] //public ActionResult<IEnumerable<string>> Get() public JsonResult Get() { string sql = "select top 100 * from dbo.infor"; DataTable datatable = DBHelper.DBExecuteByAdapter(sql); string jsonstr = JSONInterFace.DataTableToJsonWithJsonNet(datatable); return new JsonResult(jsonstr) ; } // GET api/StuInFors/5 [HttpGet("{hno}")] public JsonResult Get(string hno)//注意:参数名称必须和路由[HttpGet("")]中的template相同,否则取不到值。 { string sql = "select * from dbo.infor where [no]='" + hno + "'"; DataTable datatable = DBHelper.DBExecuteByAdapter(sql); string jsonstr = JSONInterFace.DataTableToJsonWithJsonNet(datatable); return new JsonResult(jsonstr); } // POST api/StuInFors [HttpPost] public string Post()//[FromBody] string value) { string retvalue = "addfailed"; if (Request.Form.ContainsKey("androidkey")) { //既然从Form里取值了,所以不要参数:[FromBody] string value //能取到 retvalue = Request.Form["androidkey"]; } if (!string.IsNullOrEmpty(retvalue)) { retvalue = "addsuccess"; } return retvalue; } // PUT api/StuInFors/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/StuInFors/5 [HttpDelete("{hno}")] public void Delete(string hno) { string sql = "delete from dbo.infor where [no]='" + hno + "'"; DBHelper.DBExecute(sql); } } }
部署到IIS后用Postman调用结果:
关于如何部署.net core webapi 到IIS 请看本人上一篇:https://www.cnblogs.com/longdb/p/10015302.html