前言
在很多业务场景中经常会遇到调用web api接口,并且把参数传递给web api,下面将一起了解一下如何在.net core中调用web api,并且将json字符串传递给post方法
环境和组件
环境:.net core
组件:RestSharp(可以通过NuGget组件包添加到项目组)
具体实现
1、web api方法
//注意:.net core web api支持dynamic,实例中是将请求过来的json字符串转换为了list
[HttpPost("SyncNews")]
public async void SyncNews([FromBody] List<Article> data)
{
try
{
//此处是调用entity framework把数据插入到数据库
var articleRepository = new ArticleRepository();
await articleRepository.SyncDataAsync(data);
}
catch (Exception ex)
{
//此处写log日志等
}
}
//业务方法
public async Task SyncDataAsync(List<Article> articles)
{
using (var db = new PortalManagementContext())
{
foreach (var item in articles)
{
db.Articles.Add(item);
}
await db.SaveChangesAsync();
}
}
2、调用web api(Post)
下面是调用web api的两种方式
.net core请求:
//articles为Article集合
List<Article> newaddArticleList = articles;
var ArticleServiceUrl = RandUXML.Read("ArticleServiceUrl");
var clientsharp = new RestClient(ArticleServiceUrl+"api/Article/SyncNews");
clientsharp.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
//将list集合转换为json字符串,并传递给web api
string ListJson = JsonConvert.SerializeObject(articles);
request.AddParameter("application/json", ListJson, ParameterType.RequestBody);
IRestResponse response = clientsharp.Execute(request);
Console.WriteLine(response.Content);
Ajax请求:
var settings = {
"url": weburl+"/api/Article/SyncNews",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify("json字符串"),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
3、调用web api(Get)
下面是.net core及JQuery调用web api方法
.Net Core:
var client = new RestClient(weburl+"/api/Article/GetAllArticles");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
JQuery:
var settings = {
"url": weburl+"/api/Article/GetAllArticles",
"method": "GET",
"timeout": 0,
};
$.ajax(settings).done(function (response) {
console.log(response);
});
如上就是.net core调用web api的方法,如上描述如有错漏请大家评论区直接留言,多谢