Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC website doesn't receive string from client

Client:

WebClient wc = new WebClient();
try
{
    string json = wc.UploadString("http://localhost:50001/Client/Index", "1");
    dynamic receivedData = JsonConvert.DeserializeObject(json);
    Console.WriteLine("Result: {0};",receivedData.data);
}
catch (Exception e)
{
    Console.WriteLine("Oh bother");
    Console.WriteLine();
    Console.WriteLine(e.Message);
}

Basically sends "1" to the Index action in the Client controller.

Here is the Controller:

[HttpPost]
public ActionResult Index(string k)
{
  Debug.WriteLine(String.Format("Result: {0};", k));
  return Json(new { data = k}, JsonRequestBehavior.DenyGet);
}

The result from the Client is just "Result: ;". The debug output from the controller is also "Result: ;". This means that the data is lost somewhere between the client and the site. But when I debug, Visual Studio says that there was one request.

like image 531
Mitko Rusev Avatar asked Apr 07 '17 10:04

Mitko Rusev


People also ask

How to send and receive data from web API url?

HttpClient sends and receives data from Web API URL which is hosted on the local IIS server.HttpClient can process multiple requests concurrently. [Install HttpClient Library] Search System.Net.Http and click on the install button. It will be taking few seconds for installing this Library. Now we need to Install WebAPI.Client library from NuGet

How do I create a MVC application in Visual Studio?

Create MVC Application Open Microsoft Visual studio. Click on File followed by NEW, then click on the project, select ASP.NET web application, give an appropriate name and click OK. After clicking OK, the following window will appear. select Empty and MVC Options then click OK. [Empty MVC Application]

What is the difference between entity and getasync in httpclient?

Here, Entities is nothing but the Class Library name, otherwise, you will get an error: "Are you missing a using directive or assembly reference?". GetAsync is a method of HttpClient class to send a get request to specified Uri as an asynchronous operation. Here I added SatyaWebApi project Url to Retrieve Data.

What is httpclient class in Laravel?

HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL. To access HttpClient class you need to mention namespace as mentioned below... Here, I added a strongly typed list of objects that can be accessed by Index. The employee is an entity model class.


3 Answers

By adding the header and specifying the parameter name, I've managed to get this to work (in your calling method):

 static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            try
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                string json = wc.UploadString("http://localhost:49847/Home/Index", "k=1");
                dynamic receivedData = JsonConvert.DeserializeObject(json);
                Console.WriteLine("Result: {0};", receivedData.data);
            }
            catch (Exception e)
            {
                Console.WriteLine("Oh bother");
                Console.WriteLine();
                Console.WriteLine(e.Message);
            }
        }

From MSDN:

...set the HTTP Content-Type header to application/x-www-form-urlencoded, to notify the server that form data is attached to the post.

I haven't run fiddler to check what (if any) headers are sent through by default but I suspect the reason this doesn't work without the header is the receiving client doesn't know where to find the query string parameters passed through.

From another answer on StackOverflow:

When receiving a POST request, you should always expect a "payload", or, in HTTP terms: a message body. The message body in itself is pretty useless, as there is no standard (as far as I can tell. Maybe application/octet-stream?) format. The body format is defined by the Content-Type header. When using a HTML FORM element with method="POST", this is usually application/x-www-form-urlencoded.

like image 129
Damon Avatar answered Oct 07 '22 13:10

Damon


WebAPI may be interpreting your argument as a URI argument.

Try this:

[HttpPost]
public ActionResult Index([FromBody] string k)
{
    Debug.WriteLine(String.Format("Result: {0};", k));
    return Json(new { data = k}, JsonRequestBehavior.DenyGet);
}

This tells WebAPI to expect this argument to be lifted from the body of the request (e.g. a JSON post payload)

like image 30
Clint Avatar answered Oct 07 '22 12:10

Clint


Try

            string parameters = string.Concat("k=","1");

            string url = "http://localhost:50001/Client/Index";
            using (Var wc = new WebClient()){

            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded;charset=UTF-8";

            string result = wc.UploadString(url, parameters);

            JObject obj = JObject.Parse(result);

            Console.WriteLine("Result: {0};", obj.data);               

            }`
like image 32
vsmash Avatar answered Oct 07 '22 13:10

vsmash