I'm just wondering what would be the better approach to calling a Web api method? The pros and cons?
option1.
Calling the web api from an ajax post
$.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");
}
});
or option2.
An ajax post to a client controller and then use a rest client to call the web 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");
}
});
And calling the 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);
}
If you control the api and you don't need to further enrich the API call, my personal preference is option 1 as it saves unnecessary code.
If it's an external api such as Instagram's API, I prefer option 2- as then I can enrich the API with additional info like AccessToken's that I want private (rather than embedded in the JS).
Related
I'm using net.core for the first time today and I'm trying to call an action method from an ajax call:
My Ajax call (from a normal HTML page)
$("#contactMap").click(function (e) {
e.preventDefault();
var url = "/MapObjects/mapContact";
//I've tried MapObjectsController & '#Url.Action("mapContact", 'MapObjects")'; But to no avail
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
And in my controller:
namespace myName.Controllers
{
public class MapObjectsController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult mapContact()
{
Account account = new Account();
return Json(account);
}
}
}
The 'account' is just a normal model (obvs empty in this case). All I receive is a 404 error in the console though.
As mentioned this is the 1st time I've .net Core (this is code I've written loads of times in 'normal' MVC projects) so it's possible that I'm missing something really obvious.
Thanks,
C
The first, try to call the #Url.Action() explicitly in the Ajax call :
$("#contactMap").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("mapContact", "MapObjects")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
The second, check your routing rules.
I've checked the gizillion answers to this question and for some reason I can't get this to work.
I get the error:
401 (Unauthorized)
My route is an api route guarded.
My data:
let ajaxMainTemplate = {
'mainTemplate': mainTemplate,
'templateId': templateId,
'_token': accessToken,
}
My ajax call:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
data: {
_token: ajaxData._token,
ajaxData
},
success: function(response) {
console.log(response)
}
})
I've tried the above to test based on another response. I put the token outside of the ajaxData object. I get the same error. I've also attempted:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
headers: { 'X-CSRF-TOKEN': ajaxData._token },
data: ajaxData,
success: function(response) {
console.log(response)
}
})
Same.
I've also confirmed the token is there by adding a console.log Any ideas what I'm doing wrong with this?
My url was behind the api protected route so I had to do an ajax call to login into it via ajax.
The credentials are in a variable ajaxData.
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8000/api/login',
data: ajaxData,
success: function(response) {
shopifyToken = response.success.token;
getListProducts(shopifyToken);
}
});
With the shopify token generated from this login it worked.
Iam trying to send multiple parameters with complex datatype to POST method in WebAPI but it fails with 500 server error. I will be greatful if somebody help me finding what is missing ?
Ajax:
var x={}
var y={}
$.ajax({
cache: false,
type: "POST",
data: JSON.stringify({xDto:x,yDto:y}),
url: "/api/Info/PostInfo",
dataType: 'json',
contentType: "application/json;charset=utf-8",
success: function(data) {
}
error: function(data) {
alert(JSON.stringify(data));
}
})
Action:
public IHttpActionResult PostInfo(InfoDto xDto,InfoDto yDto)
{
//post xDto and yDto to db
}
I would change the API Parameter to an InfoDto array and retrieve it from the body:
public IHttpActionResult PostInfo([FromBody]InfoDto[] xDtos)
{
}
You also have to change your JavaScript to something like this:
data: JSON.stringify([x, y])
I would like to send json data using Ext.Ajax.request() then access it in ASP.NET using Request.InputStream which is the content of the request body. I need a way to tell ExtJs to write the data in the request body as it is done while using an Ext.data.proxy.Ajax.
Specify POST method and just use the request's jsonData config:
Ext.Ajax.request({
url: 'myUrl',
method: 'POST',
params: {
requestParam: 'notInRequestBody'
},
jsonData: 'thisIsInRequestBody',
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});
If you want a record written as JSON you can use a JSON writer like this also.
var writer = Ext.create('Ext.data.writer.Json'),
record = Ext.getStore('SomeStoreID').first();
Ext.Ajax.request({
url: 'myUrl',
method: 'POST',
params: {
requestParam: 'notInRequestBody'
},
jsonData: writer.getRecordData(record),
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});
Is there an AngularJS equivalent call to this jQuery ajax POST, with contentType and setRequestHeader?
$.ajax({
url: "http://localhost/songs",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
},
success: function(data){
console.log(data);
}
});
You'll probably want to use the $http or $resource service. In the $http doc you can see the section on Setting HTTP Headers to set the SOAPAction and the default content type will be set to json already (though you should be able to override that as well).
This might get you started and I'd be interested to see other answers for a better way because this seems limited.
var module = angular.module('myApp', []);
module.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['SOAPAction'] = 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems';
});
function myController($http) {
var data = { 'value1': 1, 'value2': 2 };
$http.post('/songs', data).success(function (data) {
console.log(data);
});
}
Based on this thread I don't believe you can set the headers differently for each call but it looks like a change might be coming to the $resource service that will allow it.
Update: Must have missed it in the documentation but you can most definitely set different actions per call using $http per this post like this:
var data = { 'value1': 1, 'value2': 2 };
$http.post('/songs', data, {headers: {'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'}})
.success(function (data) {
console.log(data);
});