简体   繁体   中英

How can I pass a DTO to a Rest API in vb.net?

I have an API method in one application (written in c#) that expects a DTO object

        public IActionResult SaveProviderToOmitFromDto(RadiologyBillingProvidersToOmitDto dto)
        {
            mProvidersToOmitService.SaveFromDto(dto);
            return Ok();
        }

I need to pass the DTO object in an older vb.net application. So far I have a sub to pass a URL and DTO:

        Public Shared Sub SaveProviderToOmit(ProviderToOmit As ProvidersToOmitDto)
            Dim Url = String.Format("{0}RadiologyBilling/SaveProviderToOmitFromDto", Settings.GetApiUrlStart)
            API.SaveProviderToOmitFromDto(Url, PatchMethod, ProviderToOmit)
        End Sub

and another method to "patch" the DTO

    Public Shared Sub SaveProviderToOmitFromDto(Url As String, Method As String, ProviderToOmit As ProvidersToOmitDto)
        Dim Provider = JsonConvert.SerializeObject(ProviderToOmit)
        Dim Request = GetRequest(Url, Method, Provider.Length)
        Request.GetResponse().Close()
    End Sub

    Private Shared Function GetRequest(Url As String, Method As String, ContentLength As Integer) As WebRequest
        Dim Request = WebRequest.Create(Url)
        Request.Method = Method
        Request.ContentLength = ContentLength
        Request.ContentType = "application/json"
        Return Request
    End Function

How do I pass the DTO object to the API? I expected to need to serialize the object but how do I pass the object in the request?

I could not find any question with an accepted answer for this here on Stack Overflow, but this thread without accepted answer, solved OPs problem:

How to POST a JSON to a specific url using VB.NET?

Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType
As String, method As String) As String
Dim response As String
Dim request As WebRequest

request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = contentType
request.Method = method

Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()

Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using

Return response
End Function

To use this function

Dim data = Encoding.UTF8.GetBytes(jsonSring)
Dim result_post = SendRequest(uri, data, "application/json", "POST")

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