A 405 status code from web API after trying to send PUT data in body - asp.net-web-api

ok.
I'm using Web API to make AJAX requests.
I'm trying to send a PUT request to an action on a controller.
I'm using route attributes.
When I'm sending the data as part of the route data, everything is fine and the action gets the right info.
However, when I'm trying to send the data in the body, I get a 405 status ((Method is not allowed).
I'm also adding the [FromBody] attribute to the parameter. Here's by jQuery call:
type: 'PUT',
url: 'api/ServerQueue/activity',
data: "=2",
success: function (xhr) {
$("#load").hide();
},
error: function () {
$("#load").hide();
}
};
Here's my action:
[Route("status/{status}")]
public string PutStatus([FromBody]int status)
{
}
I placed a "RoutePrefix" on the controller body.
BTW, I'm using VS 2012.
Any idea what could be the source of the problem?

Try changing the route configuration from
[Route("status/{status}")]
to
[Route("status")]

Related

POST request doesn't get response from server in chrome but work in postman

I'am making a POST request to spring boot endpoint and wanna get data return from server.With testing my API in Postman,it works good.but when testing it in
chrome,it doesn't even get a response and chrome NETWORK bar even did't have record.
so code is simple,I can't find any problem,RestController
#PostMapping("/signup")
public User signup(#RequestBody ModelUser user){
//fetch data from DTO and craft a user
User userData=user.adapter();
//...code here omit for sake of brevity
return userData;
}
it indeed get data from ajax,when I use logger(slf4j) to debug.
and ajax:
$("#sign-up").submit(function () {
var userInfo={}
userInfo["phone"]=$("#phone").val()
userInfo["password"]=$("#password").val()
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
}).then(
function(){
//this doesn't print in console
console.log("Hello Callback is executed")
}
)
})
weird as it is,I never encounter this when I use GET request,since ajax callback is successfully called when I use GET to test a GetMapping endpoint.
oh,with lots of similar questions
AJAX POST request working in POSTMAN but not in Chrome
Angular 4 POST call to php API fails, but GET request work and POST requests work from Postman
POST response arrives in Postman, but not via Ajax?
I don't get any response status code in chrome and completely not involved CORS in question
Have you tried adding a consumes and produces media type of Json in the Java
#PostMapping(path="/signup", consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
And explicitly set the Accept header in the javascript
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
headers: {Accept : "application/json"},
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
})
I'am sorry for my poor front end skill,the main reason is that I don't understand Javascript event.
$("#sign-up").submit(function (e) {
//e.preventDefault();
var user={};
user["phone"]="187308";
user["name"]="icywater";
$.ajax({
type:'POST',
contentType:'application/json',
data:JSON.stringify(user),
url:"http://localhost:8080/test"
}).done(function(data){
console.log("Hello Callback is executed");
console.log(data)
});
});
here when I click submit It actually already submit the form and don't wait ajax code to be executed,so I should use e.preventDefault()to suppress default behavior.It's nothing
related about POST or postman ,it is about the form submit default behavior,ahh,Oolong event.
I got it when I found this page

Axios AJAX call nulls parameter

I use Vuejs to create my frontend for my project.
At the creation of one component ('TimeCapsy.vue'), I make an AJAX call to my backend like this:
created: function () {
if (verify.verify_login()) {
let token = this.$cookies.get('jwt_us_cas');
let params = {'jwt': token};
console.log(params);
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
params: queryString.stringify(params)
})
.then(response => {
console.log(response.data)
})
}
}
As you can see I use the
this.$cookies.get('jwt_us_cas');
to get the a json web token, that I set on the client at the login.
I use the queryString Library to stringify my parameters for my request.
I also tried it without the queryString.stringify(params) call, but I get the same error, e.g. the parameter still turns into null.
When I look at the console log, where I check the params variable, I get this output:
{jwt: "my token comes here"}
So I can see, that it gets the correct value from the cookie.
But when I check the answer from my backend (PHP), I get this error:
Undefined index: jwt in <b>D:\casb\public\index.php</b> on line <b>52</b>
Of course I know that it means, that jwt is null, but I can't understand why.
As I said, right before I make the call I check the params and it shows the token.
I checked the endpoint with Postman and the token as the jwt parameter and it returned a successfull call with the correct answer.
A correct answer is basically just a nested object with some information in it.
My PHP endpoint is pretty basic too:
Router::add('/getuserinfoobject', function () {
$response['response'] = User::getUserInfoObject($_POST['jwt']);
echo json_encode($response);
}, 'post');
So I guess that right before or in my call it nulls my parameter. But I can't understand how, since I make a lot of requests and never had this problem.
From axios docs
params are the URL parameters to be sent with the request
Which means, you should get the value with PHP $_GET.
Or $_REQUEST (which stores both $_GET, $_POST. Also $_COOKIE).
The other hand, you can use data key as docs says
data is the data to be sent as the request body
Only applicable for request methods PUT, POST, and PATCH
So the value would be available in $_POST
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
data: {
jwt: token
}
})

React js AJAX sends sometimes GET instead of POST and getting 304 strange

I've got a problem and I have no idea why it appears. The circumstances of its appearance are very strange for me...
I've got a POST REST service /login. It expects json {"email":email,"password":password}. I am using ajax and everything works correctly... except for the case when email (is in real format) contains '#' sign and some letters before and after( I know it is strange but only in this case such error appears). When I pass email i.e "mum#mum.com" then few things are happening:
I see that browser sends GET request instead of POST and obtains 304 http status
In the browser console I see infomation "The development server has disconnected. Refresh the page if necessary" and page refreshes automatically
The above things happen only when email is in format I described above.When I pass "aaa" or "aaa#" as email everything works correctly(browser sends POST request and I don't get error in console).
I honestly have no idea why this happens... would be extremely grateful for your help and I will answer all your questions concerning this.
PS.
When I use REST web service tool in IntellJ everything always works fine.
handleLogin() {
const input = {
email: this.state.email,
password: this.state.password
};
$.ajax({
url: CONST.USER_SERVICE + "/login",
type: "POST",
data: JSON.stringify(input),
contentType: "jsonp"
})
.fail(function () {
alert("Wrong data");
})
.always(function (arg1, arg2, arg3) {
if (arg3.status === 200) {
alert("ok!");
}
}.bind(this));
}
Try making the ajax request like data: input without stringify. Ajax expects an object.

Ajax POST to WCF Rest CORS-compliant WebService throws error 405

I'm doing some test over WCF REST WebServices and i'm stuck with the POST call.
I've created a webservice that exposes some test data about the good ol' Northwind DB and since i wish to consume it locally from a test HTML page and since i'd like to test CORS capabilities, i made it CORS compliant by following these instruction http://enable-cors.org/server_wcf.html.
Unfortunately problems comes out when i make POST calls.
Unlike GET calls (works very well), POST call throws this error:
What the hell is it? it seems that "Access-Control-Allow-Origin" header is not correctly managed client-side, beacuse in my EnableCrossOriginResourceSharingBehavior WCF class, the method "ApplyDispatchBehavior" (it filter "Access-Control-Allow-Origin" headers of the arrival requests) is hit when i make a POST call, but then Ajax call fails.
This is my jQuery Ajax post command:
//Create new object
var item = {
"CustomerId": "0",
"CompanyName": "prova"
};
//Push object
$.ajax({
type: "POST",
url: 'http://localhost:3434/NorthwindService.svc/Customer/Create',
crossDomain: true,
headers: {'Access-Control-Allow-Origin' : '*'},
data: JSON.stringify(item),
success: function (data) {
alert('ok!');
},
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
This is my WCF service Visual Studio 2013 project.
To test it, you only have to set "NorthwindConnectionString" in web.config to an existing one. The webservice method that i've problem with, is the POST to the "http://localhost:3434/NorthwindService.svc/Customer/Create" method, all the others works fine.
This is a preview of my method contract:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "Customer/Create", BodyStyle=WebMessageBodyStyle.WrappedRequest)]
void NewCustomer(CustomerDTO customer);
Thanks in advance.
I don't know what's going on, but thanks to supertopi and his link, i did the right steps to make it works. Unfortunately implementing all things discussed in here How to handle Ajax JQUERY POST request with WCF self-host did't works. I continued to get "405 Method not allowed" even by creating a new project.
The only thing that works in my case is the following:
1) Implement CustomHeaderMessageInspector and EnableCrossOriginResourceSharingBehavior classes and edit web.config as exposed in http://enable-cors.org/server_wcf.html.
2) Create in the service contract the following method:
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
3) Implementing it empty.
public void GetOptions()
{
}
It sounds crazy, but it actually works.
If i remove GetOptions() operation contract, i continue to get 405 error on my client. If i implement it like indicated by supertopi's link (obviously after remove all stuff created in the step 1), it doesn't work either.
Hope it helps.
Your HTTP Request Method is defined OPTIONS instead of POST.
That is why you get HTTP Response 405 Method not Allowed (no handler for OPTIONS request)
Change the type parameter in jQuery ajax constructor to "POST" and the request is routed to correct handler.

Handling the Request redirects in ASP.Net MVC 2 with ajax requests

I have developed an ASP.NET MVC2 application and in that i have a login feature implemented.
I have other views that have ajax calls. At times, i find the ajax calls displaying the login page.
In an attempt to get rid of this problem, i have tried to simulate the situation, but the response code that i get from my application was 200 which is OK
I am using ASP.Net MVC2. Why am i getting 200, where i should be actually getting a 302 server redirect for login page redirection from my current view.
Guide me to handle this situation.
Why am i getting 200, where i should be actually getting a 302 server
redirect for login page redirection from my current view.
It's because jQuery follows the redirect and you end up with 200 and the login page. I would recommend you the following article which illustrates a very elegant way to configure ASP.NET to send 401 status code for unauthenticated requests assuming this request was made using an AJAX call. Then your client code will look like this:
$.ajax({
url: '/foo',
type: 'POST',
data: { foo: 'bar' },
statusCode: {
200: function (data) {
alert('200: Authenticated');
// Do whatever you was intending to do
// in case of success
},
401: function (data) {
alert('401: Unauthenticated');
// Handle the 401 error here. You can redirect to
// the login page using window.location.href
}
}
});

Resources