![](/img/trans.png)
[英]how to get data from asp.net api restful webservice from node.js server?
[英]How to call node.js REST API from .NET
如果我将jQuery代码放在html页面内的script标记内,然后将html页面拖到Web浏览器中,则将调用URL中指定的API,并以JSON格式返回响应。 所以这很好。
我之所以想使用.NET来调用node.js中创建的其余API,是因为我想使用Visual Studio中存在的单元测试实用程序。
因此,当我开始单元测试时,应该对node.js中的REST API进行调用,然后可以使用assert.AreEqual检查返回的json格式的内容。
我已经在Google上搜索了很多,并且在ASP.NET Web API 2中有几个关于单元测试控制器的示例,但是我不想对单元测试控制器进行单元测试。 当我开始单元测试时,我只想调用REST API(由node.js制造)。
我假设以我想要的方式使用.NET可能很少。
如果无法以我想要的方式使用.NET和单元测试,我将使用另一个测试框架。 我希望从这里得到一些帮助。
希望你明白我的意思。
$.ajax({
type: 'GET',
url: 'http://10.1.23.168:3000/api/v1/users/1',
dataType: 'json',
async: false,
headers: {
'Authorization': 'Basic ' + btoa('DEFAULT/user:password')
},
success: function(response) {
//your success code
console.log(response);
},
error: function (err) {
//your error code
console.log(err);
}
});
非常感谢
基本上,您需要做的就是以与使用jQuery调用它相同的方式,从C#测试代码中调用node.js的API。 有几种方法可以做到这一点:
通常,我建议使用方法2。
此代码段应足以使您到达所需的位置。
using(var client = newHttpClient())
{
client.BaseAddress = newUri("http://localhost:55587/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));
//GET Method
HttpResponseMessage response = awaitclient.GetAsync("api/Department/1");
if (response.IsSuccessStatusCode)
{
Departmentdepartment = awaitresponse.Content.ReadAsAsync < Department > ();
Console.WriteLine("Id:{0}\tName:{1}", department.DepartmentId, department.DepartmentName);
Console.WriteLine("No of Employee in Department: {0}", department.Employees.Count);
}
else
{
Console.WriteLine("Internal server Error");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.