I am facing an issue while login . Registration is working fine.
Tech stack - HTML/AJAX/JQuery->Resteasy (Wildfly 10.1.0 Final)
I have the url - https://www.test.com/login.html - (actual URL name is modified)
When I am submitting the form with method type = "POST", it always throws, 405 Method not allowed.
Below is the section of the code:
submitHandler: function(form) { // fires only when form is valid
var loginData = formJSONLoginData();
$.ajax({
url:"https://"+getUrl()+"/curAuthService/curAuth/authenticateUser/v1",
type : "POST",
dataType : "json",
contentType: "application/json",
data: loginData,
success : function(response) {
},
error: function( xhr, status, error ){
}
});
return false;
},
And the Rest API is below:
#Path("/curAuth")
public class FHAuthResource {
#POST
#Path("/authenticateUser/v1")
#Produces("application/json")
#Consumes("application/json")
public String authenticateUser( AuthVO authVO ) {
}
}
It would be great help if someone can help/advice on where I am going wrong.
Registration is in similar format and it works fine.
Ultimate stupid mistake. Missed out "extends Application" for the Application file which is required for resteasy.
Related
I have a project with areas and would like to post a view model as JSON to a controller method.
This is what I have, with performance being generated in the default area and passed to the view in area SeatSelection:
$("#addToCartButton").click(function () {
var json = #Html.Raw(Json.Encode(performance));
$.ajax({
url: 'https://#(Request.Url.Host)/SeatSelection/Home/AddToCart',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
And the action method for testing:
[System.Web.Http.Route("SeatSelection_AddToCart")]
[System.Web.Http.HttpPost]
public JsonResult AddToCart(PerformanceViewModel performance)
{
return Json(performance.Name);
}
I created the following route:
context.MapRoute(
"SeatSelection_AddToCart",
"SeatSelection/Home/AddToCart",
new { action = "AddToCart", controller = "Home", id = UrlParameter.Optional },
namespaces: new string[] { "myProject.Areas.SeatSelection.Controllers" }
);
But all I get is a internal server error 500. I also tried to use [FromBody] and setting a breakpoint to the method, but it is not invoked. I can't figure out what's wrong or missing, please help.
UPDATE
This is the json / performance:
PerformanceID=00000000-0000-0000-0000-000000000000&Name=Performance+15&StartDate=%2FDate(1360364400000)%2F&EndDate=%2FDate(1500328800000)%2F&LatestDateBookable=%2FDate(1450911600000)%2F&Organizer=Organizer+15&Location=Location+15&Availability=75&IsFull=false&IsBookable=true&HasPrice=true&BookableSeats=11&BookedSeats=94&Description=Description+of+Performance+15&Price=443
I found an error: "invalid json primitive: performanceid"
First of all, I would recommend you to use #Url.Action helper method instead of generating url like this: https://#(Request.Url.Host)/SeatSelection/Home/AddToCart.
Secondly, always validate params which comes from the browser. return Json(performance.Name) looks suspicious. What is performance will be null? This might be a problem of your internal server error 500.
If this is not a problem then try to send string instead of JSON to the server and validate and parse JSON on the server side.
You can use Url.Action method like this. I suppose SeatSelection is an area in your project.
$.ajax({
url: '#Url.Action("AddToCart", "Home", new { Area = "SeatSelection"})',
I'm trying to consume json data from a web API in .NET. I tried by two ways, with web API and returning Json with a MVC controller but I can't consume from any of both. I only can consume it from a view inside my project, but when I try to consume with a html page outside my project it throws an error.
It is hosted in azure. Here is the code of the Action.
public ActionResult PreguntasById(int id)
{
var emp = db.pregunta_area.Where(i => i.fk_pregunta == id).Select(e => new
{
id = e.fk_pregunta,
pregunta = e.Preguntas.pregunta,
area = e.fk_area
}
).ToList();
return Json(emp, JsonRequestBehavior.AllowGet );
}
And my AJAX petition.
function siguientePregunta()
{
$("#pregunta").remove();
$.ajax({
type: "GET",
dataType: 'json',
url: 'http://carrierintegrator.azurewebsites.net/Preguntas/PreguntasById/'+contador,
async: true,
success: function (response) {
$("#pregunta-content").append("<h6 id='pregunta'>"+response[0].pregunta+"</h6>");
console.log(response);
},
error: function (obj, error, objError) {
alert("Error interno: " + objError);
console.log(id_pas);
}
});
contador++;
}
Also I tried to quit the dataType but it's useless. I don't know what it's going wrong.
I'm doign the same in the Web API Controller but i'm having the same error.
I have the following scenario: I have a kendo.dataSource which is populated via read request to a WebApi Controller. In addition to the read, I am sending a couple of parameters, which then I use in my controller to do some server logic. I was able to send as many simple parameters as I want via the parameterMap property of the transport function. Till now it was a simple get request. However now I need to send additional json object to the controller as a parameter. I read that I have to transform the Get request to Post and put the Json onto the body of the request but I don't know how to do it.
The code that I have so far:
var gridDataSource = new kendo.data.DataSource({
type: 'odata-v4',
transport: {
read: {
url: wave.alarmsAndEvents.api('api/alarmsAndEventsSearch/post'),
type: "POST",
data: {
SearchModel: JSON.stringify(vm.searchModel)
},
contentType: 'application/json; charset=utf-8',
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.startDate = kendo.toString(vm.selectedTimeInterval.start, "G");
data.endDate = kendo.toString(vm.selectedTimeInterval.end, "G");
data.alarmsToDisplay = vm.maxRecords;
}
return kendo.stringify(data);
}
},
pageSize: vm.maxRecords,
error: function (e) {
alert(e.xhr.responseText);
}
});
The SearchModel is the thing that I want to send as JSon. The rest are simple DateTime and int parameters.
My controller:
[HttpPost]
public IQueryable<AlarmsSearchViewModel> Post(DateTime startDate, DateTime endDate, int alarmsToDisplay, [FromBody]JToken jsonbody)
{
....
return something;
}
I end up with Not Found 404, but I am pretty sure that I have messed up the parameters. And from the Network window I can see that the json object is not sent at all. Any help will be much appreciated!
I have problem with json which is sent from the sencha touch client to the rest web abi web service.
When i send POST request from Sencha it looks like:
var paramsData = Ext.encode({
FormId: '5',
WorkcardId: 'a1234',
FormDataSet: 'dataset'
});
Ext.Ajax.request({
url: JsonTestClient.app.webserviceUrl',
scope: this,
method: 'POST',
headers: { 'Authorization': 'Bearer ' + jsonToken.access_token },
params: paramsData,
contentType: "application/json;charset=utf-8",
success: function (response, options) {
//
},
failure: function (response, options) {
//
}
});
and paramsData value is : "{"FormId":"5","WorkcardId":"a1234","FormDataSet":"dataset"}"
However on WebApi RestService in the method
[System.Web.Http.HttpPost]
public string SaveForm([FromBody] JObject jsonData)
{
//
}
jsonData looks like
{
"{\"FormId\":\"5\",\"WorkcardId\":\"a1234\",\"FormDataSet\":\"dataset\"}": ""
}
So it seems like my initial json is wrapped in another object and is used as a key value.
Any ideas what can be wrong?
thanks.
From client site(sencha),Can you verify JSON in the http request body?
From server side,did you write all the contract for that method like what kind of parameter it can accept?
RequestFormat = WebMessageFormat.Json,
Above property should be placed inside the interface(or directly inside class if you did not have interface) that defines the contract regarding the input parameter.
Thanks to kasharma, i payed attention to how looks FormData in the sencha touch request.
From that i found a solution. I had to add
jsonData: paramsData,
to the post request
I have a web service method similiar to this:
#Path("/insert_update")
#POST
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
public Object insert(User obj) {
...(insert and return object)
}
And I want to call this method from jquery, using ajax. I've tried something like this:
var rootURL = "http://Path/to/my/web/service";
function insertUpdate() {
var user = {'name' : $("#name").val(),
'surname' : $("#surname").val(),
'surname1' : $("#surname1").val(),
'usertxt' : $("#usertxt").val(),
'password' : $("#password").val() };
$.ajax({
url : rootURL + "/insert_update",
type : "POST",
contentType: 'json',
dataType : "json",
data : user,
success : function(data) {
alert(JSON.stringify(data));
},
error : function(data) {
}
});
}
Is this code correct? When I try to use it I get this response:
Failed to load resource: Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
XMLHttpRequest cannot load ... . Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
I hope you can help me.
Greetings.
UPDATE
The web service is in the same machine, but in other port. I run the web service project on a WebSphere Application Server and then I only open the HTML file to test my code.
I have other method I don't have problem with, like this:
#Path("/all")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Object all() {
...(get all users)
}
And the JQuery method for this code:
function all() {
$.ajax({
url : rootURL + "/all",
type : "GET",
dataType : "json",
success : function(data) {
$("#tabla tbody:last").empty();
$.each(data.data, function(i, item) {
$("#tabla tbody:last").append("<tr><td>"+item.id+"</td><td>"+item.name+
"</td><td>"+item.surname+"</td><td>"+item.surname1+"</td><td>"
+item.usertxt+"</td><td>"+item.password+"</td></tr>");
});
},
error : function(data) {
}
});
}
This works fine, I have no problem...but I had to donwload an extension for Chrome to test locally, Allow-Control-Allow-Origin.
Why with GET method I have no problem and with POST method yes???
Greetings.