![](/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.