Home > Back-end >  Null parameter on API POST
Null parameter on API POST

Time:02-24

Web Controller:

public void SignIn(UserInfo user, IList<string> roleList, bool rememberMe = false)
{
    Audit audit = new Audit()
        {                
            UserName = user.UserName,
            Role = roleList[0].ToString(),
            ControllerAccessed = "Login",
            MethodAccessed = "Login",
            TimeAccessed = DateTime.UtcNow,
            IsLogin = true,               
            Is_Report = false,
            Report_Type = null,
            Report_Name = null
        };
     PostAPIData<int>(apiBaseUrl   "api/AuditAPI/LogUIAudit", audit);
}

public class Audit
{        
    public string UserName { get; set; }
    public string Role { get; set; }        
    public string ControllerAccessed { get; set; }
    public string MethodAccessed { get; set; }
    public DateTime TimeAccessed { get; set; }
    public bool IsLogin { get; set; }
    public bool Is_Report { get; set; }
    public string Report_Type { get; set; }
    public string Report_Name { get; set; }
    
}

public T PostAPIData<T>(string url, object obj)
{
    using (HttpClient client = new HttpClient())
    {
        var responseTask = client.PostAsJsonAsync(url, obj);
        responseTask.Wait();
        var result = responseTask.Result;
    }
}

In above SignIn method, I'm passing 2 different api calls with respective model classes. So I defined it as obj in the PostAPIData method. and one of the url is https://localhost:44306/api/AuditAPI/LogUIAudit. When this code hits the below API Controller, parameters turns empty:

API Controller:

[Route("api/AuditAPI/LogUIAudit")]
[HttpPost]
public int LogUIAudit(Audit AuditEntry)
{
} 

I tried below conversions. But none of them works.

1:

StringContent content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
var responseTask = client.PostAsJsonAsync(url, content);    

2:

StringContent content = new StringContent(JsonConvert.SerializeObject(AuditEntry), Encoding.UTF8, "application/json");
var responseTask = client.PostAsync(url, content); 

3:

Audit AuditEntry = (Audit)obj;
StringContent content = new StringContent(JsonConvert.SerializeObject(AuditEntry), Encoding.UTF8, "application/json");
var responseTask = client.PostAsync(url, content);

Both client and server is running. But when I debug the code, all the properties of that model class are shown as null.

CodePudding user response:

In order to get your data in your API Controller, you should use the FromBody attribute to bind your model correctly:

[Route("api/AuditAPI/LogUIAudit")]
[HttpPost]
public int LogUIAudit([FromBody]Audit AuditEntry)
{

}
  • Related