Hasan A Yousef Hasan A Yousef - 1 month ago 7
C# Question

Send and receive data in controller from Static files without binding to model

I need to send/receive data to/from C# API without using a model.

I've for testing purposes, the below JS:

fetch('/login', {
method: 'post',
body: JSON.stringify({
email: 'hasan@gmail.com', //document.getElementById('email').value
pswd: '1234' //document.getElementById('answer').value
})
})
.then(function(response) {
return response.text();
// return response.json();
}).then(function(text) {
// console.log(text);
});


where I need to send the username and password, and need the server to send back some confirmations.

The Controller used in C# is:

[Route("/login")]
public class FetchController
{
[HttpPost]
public async Task Post(String loginParam)
{
if (loginParam != null)
{
Console.WriteLine("Login Data Recieved");
}
else
{
Console.WriteLine("Login Data is NULL");
}
Console.WriteLine(loginParam);
var response = _httpContextAccessor.HttpContext.Response;
response.Headers.Add("Content-Type", "text/event-stream");
response.StatusCode = 200;
await response
.WriteAsync($"user logged in at {DateTime.Now}\r\r");
response.Body.Flush();
}
}


Here I keep getting the
Login data is NULL
, I know this is as I did not bind the login data to
Model class
, so how can I make the above working
WITHOUT
using
MODEL binding

E.B E.B
Answer

Note that you must match parameter name, and try to mark the param as [FromBody], since the webapi will try to read that as fromUrl.

Here is a working sample:

Javascript/JQuery

    function callFnc() {
        var loginParam = JSON.stringify({ email: 'hasan@gmail.com', pswd: '1234' });
        $.post("/Fetch/login", { loginParam : loginParam })
              .done(function (data) {
                  alert("Data Loaded: " + data);
              });
    }

C#

    [HttpPost]
    public ActionResult Login(string loginParam)
    {
        if (loginParam != null)
        {
            Console.WriteLine("Login Data Recieved");
        }
        else
        {
            Console.WriteLine("Login Data is NULL");
        }
        Console.WriteLine(loginParam);
        return new JsonResult() { Data = "Ok" };
    }

Here is the result:

enter image description here

ps: the sample is in mvc instead of webapi, however they are similar

Edit with Fetch

Note: Your problem in here is not in c#, it is all in fetch APi, if you can, get rid of it.

Here is an Example I made using Fetch,

Javascript

    function useFetch() {
        var loginParam = JSON.stringify({ email: 'hasan@gmail.com', pswd: '1234' });
        fetch('/Home/login', {
            method: 'post',
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
            body: loginParam
        });
    }

C#

    [HttpPost]
    public JsonResult Login([FromBody]object loginParam)
    {
        if (loginParam != null)
        {
            Console.WriteLine("Login Data Recieved");
        }
        else
        {
            Console.WriteLine("Login Data is NULL");
        }
        Console.WriteLine(loginParam);
        return Json("OK");
    }

Result enter image description here

and Project