什么是实施网络的更好方法 api
Whats a better approach to implementing web api
我只是想知道调用 Web api 方法的更好方法是什么?优缺点?
选项1。
从 ajax post
调用网络 api
$.ajax({
url: 'localhost/api/user/adduser',
type: 'POST',
data: JSON.stringify({ Id: Id }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function () {
alert("error");
}
});
或选项2。
一个 ajax post 到客户端控制器,然后使用 rest 客户端调用网络 api
$.ajax({
url: 'user/adduser/',
type: 'POST',
data: JSON.stringify({ Id: Id }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function () {
alert("error");
}
});
并调用 api
public ActionResult addUser(int id)
{
var api = new RestClient("http://localhost:60081/api/");
var request = new RestRequest("/user/adduser", Method.POST);
var result = new User();
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(id);
var resp = api.Execute(req);
}
如果您控制 api 并且不需要进一步丰富 API 调用,我个人的偏好是选项 1,因为它可以节省不必要的代码。
如果它是外部 api,例如 Instagram 的 API,我更喜欢选项 2- 这样我就可以使用我想要私有的附加信息(例如 AccessToken)来丰富 API(而不是而不是嵌入在 JS 中)。
我只是想知道调用 Web api 方法的更好方法是什么?优缺点?
选项1。 从 ajax post
调用网络 api $.ajax({
url: 'localhost/api/user/adduser',
type: 'POST',
data: JSON.stringify({ Id: Id }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function () {
alert("error");
}
});
或选项2。 一个 ajax post 到客户端控制器,然后使用 rest 客户端调用网络 api
$.ajax({
url: 'user/adduser/',
type: 'POST',
data: JSON.stringify({ Id: Id }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function () {
alert("error");
}
});
并调用 api
public ActionResult addUser(int id)
{
var api = new RestClient("http://localhost:60081/api/");
var request = new RestRequest("/user/adduser", Method.POST);
var result = new User();
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(id);
var resp = api.Execute(req);
}
如果您控制 api 并且不需要进一步丰富 API 调用,我个人的偏好是选项 1,因为它可以节省不必要的代码。
如果它是外部 api,例如 Instagram 的 API,我更喜欢选项 2- 这样我就可以使用我想要私有的附加信息(例如 AccessToken)来丰富 API(而不是而不是嵌入在 JS 中)。