Object becomes null after calling HTTPClient.PostAsJsonAsync to access Web Api in web form

New Contributor

In my web form (ASP .Net 4.8, VB .Net), I have calling the following function from code-behind submit sales transaction via web api:

 

Public Async Function SendSale(fs As SaleTxnReqModel) As Task(Of SaleTxnRespModel)
Dim returnData As SaleTxnRespModel = New SaleTxnRespModel()
Dim apiUrl = "Sales/SendSale"
Dim resultRemark As String = String.Empty

Try

Using client = New HttpClient()
client.BaseAddress = New Uri(AppComp.NormalizeBaseUrl(constWebApiUri))
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))


 Dim jsonString As String = JsonConvert.SerializeObject(fs)
Dim content = New StringContent(jsonString, Encoding.UTF8, "application/json")

 

Dim response As HttpResponseMessage = Await client.PostAsJsonAsync(apiUrl, content)

 

returnData = Await response.Content.ReadAsAsync(Of SaleTxnRespModel)()

 

If Not response.IsSuccessStatusCode Then
resultRemark = AppComp.SetWebServStatusText(response.StatusCode)
End If

End Using


Catch ex As Exception
resultRemark = AppComp.GetExceptionMessage(ex)
Finally
returnData.REMARK = resultRemark
End Try

Return returnData
End Function

 

At the receiving web api, the request object has become null. 

 

[Route("SendFuelSale")]
[HttpPost]
public IActionResult SendFuelSale(SaleTxnReqModel txn)
{
// Process sales transaction...

}

 

I have tried using SendAsync method and it worked:

 

Dim jsonString As String = JsonConvert.SerializeObject(fs)
Dim content = New StringContent(jsonString, Encoding.UTF8, "application/json")

Dim request = New HttpRequestMessage(HttpMethod.Post, apiUrl)
request.Content = content
Dim response As HttpResponseMessage = Await client.SendAsync(request).ConfigureAwait(False)

 

I just wonder what went wrong when using PostAsJsonAsync  method.

 

Any idea? Please adivse. Thanks.

2 Replies

Hi @Ryan_Ong,

Thanks for posting your issue here.

However this platform is used for how-to discussions and sharing best practices for building any app with .NET.Since your issue is a technical question, welcome to post it in Microsoft Q&A forum, the support team and communities on Microsoft Q&A will help you for any technical questions.
Besides, it will be appreciated if you can share it here once you post this technical question Microsoft Q&A.
Best Regards,
Lan Huang

@LanHuang Noted. I will post my question in MS Q&A platform. Thanks.