asp.net core WebAPI之Restful
在新建完asp.net core webapi项目
并且将Route改成[Route("[controller]/[action]")]后
1.GET请求之无参方法
[HttpGet] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); }
对应请求url:http://localhost:7056/haha/WeatherForecast/Get
2.GET请求之有参方法
[HttpGet] public WeatherForecast GetById(string id) { if (id == "1") { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray().First(); } else { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = 11111, Summary = "dsadsaa" }) .ToArray().First(); } }
对应请求url:http://localhost:7056/haha/WeatherForecast/GetById?id=aa
3.POST请求之有参方法
[HttpPost] public string Add(string ds,int dsadas,WeatherForecast weatherForecast) { return "添加成功"; }
对应请求url:http://localhost:7056/haha/WeatherForecast/Add?ds=aa&dsadas=1234
对应报文体:{
"date": "2023-02-24T11:37:37.030Z",
"temperatureC": 0,
"summary": "string"
}
4.PUT请求之有参方法
[HttpPut] public string Update(WeatherForecast weatherForecast) { return "更新成功"; }
对应请求url:http://localhost:7056/haha/WeatherForecast/Update
对应报文体:{
"date": "2023-02-24T11:37:37.030Z",
"temperatureC": 0,
"summary": "string"
}