简体   繁体   中英

Unable to send a http POST request to ASP.NET web api Controller using javascript

There is a node.js server and I'm going to call my web api controller when a client connected with node.js server using a websocket. Im' using socket.io to connect client with node.js server, then node.js server sends a xhr POST request to web api controller. but getting the response as, "{"Message":"No HTTP resource was found that matches the request URI ' http://localhost:4928/api/Player '.","MessageDetail":"No action was found on the controller 'Player' that matches the request."}"

Web API Method

    public class PlayerController : ApiController
{
      public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    public string Post(string value)
    {
        return value;
    }
}

Node.js

 var app = require('express')();
var http = require('http').Server(app);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var querystring = require('querystring');
var io = require('socket.io')(http);
io.on('connection', function (socket) {
    console.log('A user connected ' + socket.handshake.address);
    PostRequest(socket.handshake.address);
    //Whenever someone disconnects this piece of code executed
    socket.on('disconnect', function () {
        console.log('A user disconnected ' + socket.handshake.address);
    });
});


function PostRequest(data) {

    var url = "http://localhost:4928/api/Player";
    var params = "value=" + data;/* querystring.stringify({ "value": data })*/
    xhr.open('POST', url, true);
    xhr.onreadystatechange = function () {//Call a function when the state changes.
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
        }
        console.log(xhr.responseText);

    }
    xhr.send(querystring.stringify({ value: "sss" }));

}


http.listen(3000, function () {
    console.log('listening on *:3000');
});

Anyway this is working when I'm call the get method sending a xhr get request

You need to inform Web API to look for the value parameter in the Request body since you're not sending data via query string. Try modifying your Post action signature:

public string Post([FromBody]string value)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM