I have this web api controller:
public class LoginController : ApiController
{
private mw2devnew15Entities db = new mw2devnew15Entities();
[System.Web.Http.HttpGet]
public string Post()
{
string authenticationToken = "";
return authenticationToken;
}
[System.Web.Http.AcceptVerbs("GET", "POST")]
public HttpResponseMessage Post(JObject data)
{
dynamic json = data;
LoginForm loginF = new LoginForm();
loginF.username = json.username;
loginF.password = json.password;
return Request.CreateResponse(HttpStatusCode.OK);
}
}
I'm able to post correctly with this ajax call:
jQuery.ajax({
type: "POST",
url: "http://localhost:5832/api/Login",
data: JSON.stringify({ username: 'joep11aul1234', password: '1212213' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
}
});
But when I'm trying to use Postman to place POST call, the JObject is null.
Any idea why?
Using Postman you're not reproducing the same request as your JavaScript code since you posting the parameters in the query string. What you shoud do instead is something like this:
Add a content type header with the value of application/json:
and for your request body select raw and then add your JSON:
this will send the following request same as your JavaScript code:
POST /api/Login HTTP/1.1
Host: localhost:5832
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 4bf25ded-7548-77f9-3389-fa16a5d50087
{ "username": "joep11aul1234", "password": "1212213" }
Related
Here is any Jquery ajax POST request;
$.ajax({
type: "POST",
url: "/Customers/GetAll",
contentType: "application/json",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
Here is my Controller Action Method which requested by ajax above;
public IActionResult GetAll()
{
//Method body...
}
How can I get the dataType of any ajax request in base controller or action method?
Try to get accept in headers:
action:
public IActionResult GetAll()
{
string dataType = HttpContext.Request.Headers["accept"].ToString();
//Method body...
}
The headers can be retrieved on the HttpContext object.
if(HttpContext.Request.Headers.TryGetValue("accept", out var acceptHeaders)) {
var firstAcceptHeader = acceptHeaders.FirstOrDefault();
}
You can also access the header value using indexing Headers["accept"], but be aware, that if there is no accept header, for whatever reason, this will throw a NullReferenceException.
On my server side project I have a method looking like this:
#RequestMapping(method=RequestMethod.POST, path="mypath")
public String myMethod(String myString, Authentication authentication) {
//Here myString is null!!!
}
On my client side program I try to call the method with this code:
var text="a long string...";
Ext.Ajax.request({
url: 'blablabla/mypath',
method: 'POST',
params: {myString: text},
success: function(response, opts) { },
failure: function(response, opts) { }
});
The problem is that the parameter myString becomes null when it gets to the server.
I'm trying to using FormCollection instead of a model.
I created my AJAX request:
myData = {
id: '1',
name: $("#name").val()
};
$.ajax({
type: "GET",
url: '/testController/Test',
data: JSON.stringify(myData),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// do something
},
error: function (erro) {
console.debug(erro);
}
});
My controller with FormCollection
[HttpGet, ValidateInput(false)]
public JsonResult Test(FormCollection formData)
{
string name = formData["name"].ToString();
}
However, my formData is always null. Does anyone know why?
Thanks
If you are making GET request, you are actually making this request. And you need to access the parameter by Request['id'] & Request['name'].
Request URI: /testController/Test?id={data_id}&name={data_name}
Request Body: <empty>
However, if you are making POST request, you are making this request:
Request URI: /testController/Test
Request Body: {"id":"data_id","name":"data_name"}
The request body is parsed and you can access the data through FormCollection. That's why FormCollection is always null when you make GET request.
We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});
You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});
The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}
Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter
I create a simple MVC Controller action, that takes some json data - then return true or false.
[AllowCrossSiteJson]
public JsonResult AddPerson(Person person)
{
//do stuff with person object
return Json(true);
}
I call it from javascript:
function saveData(person) {
var json = $.toJSON(person); //converts person object to json
$.ajax({
url: "http://somedomain.com/Ajax/AddPerson",
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("ok");
}
});
}
Everything works as long as I am on the same domain, but as soon as I call it from another domain, I run into problems.
On the controller is an action filter "AllowCrossSiteJson" that sets the header "Access-Control-Allow-Origin" to "*", allowing any origin to access the controller action.
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
However - I then get this error in firebug, when calling across domains:
OPTIONS http://somedomain.com/Ajax/AddPerson?packageId=3 500 (Internal Server Error)
XMLHttpRequest cannot load http://somedomain.com/Ajax/AddPerson. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
What is wrong here?
I have been looking through possible solutions for hours, and it seems to be something to do with jquery using OPTIONS (not POST as I would expect).
If that is indeed the problem, how can I fix that?
To fix the Access-Control-Allow-Origin error, you need to include the following header in your response:
Access-Control-Allow-Headers: Content-Type
Basically, any "non-simple" header needs to be included as a comma-delimited list in the header above. Check out the CORS spec for more details:
http://www.w3.org/TR/cors/
"Content-Type" needs to be included because "application/json" does not match the values defined here:
http://www.w3.org/TR/cors/#terminology
I'd recommend you JSONP, it's the only really cross browser and reliable solution for cross domain AJAX. So you could start by writing a custom action result that will wrap the JSON response with a callback:
public class JsonpResult : ActionResult
{
private readonly object _obj;
public JsonpResult(object obj)
{
_obj = obj;
}
public override void ExecuteResult(ControllerContext context)
{
var serializer = new JavaScriptSerializer();
var callbackname = context.HttpContext.Request["callback"];
var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj));
var response = context.HttpContext.Response;
response.ContentType = "application/json";
response.Write(jsonp);
}
}
and then:
public ActionResult AddPerson(Person person)
{
return new JsonpResult(true);
}
and finally perform the cross domain AJAX call:
$.ajax({
url: 'http://somedomain.com/Ajax/AddPerson',
jsonp: 'callback',
dataType: 'jsonp',
data: { firstName: 'john', lastName: 'smith' },
success: function (result) {
alert(result);
}
});