locked
Passing multiple POST parameters RRS feed

  • Question

  • User944339287 posted

    Hi guys... can guide me on how to modify my existing code in order to input the following JSON string?

    * I got no idea how to input the OrderList

    {
        "APIKey" : "b7f3ac51f3a9c-043ed53-4453e0-873-2c151f0cf",
        "Status" : "Approved",
        "TotalAmount" : "150.50",
        "CustomerID" : "CO5821",
        "SalesDate" : "2020-05-28 18:25:00",
        "OrderList" : [{
            "OrderType" : "Parcel",
            "OrderAmount" : "50.50",
            "OrderStatus" : "Confirmed"
        },
        {
            "OrderType" : "Gift",
            "VoucherCode" : "WEE12345",
            "OrderAmount" : "100.00",
            "OrderStatus" : "Confirmed"
        }]
    }

    CODE BEHIND:

        Private Function sales() As Boolean
    
            Dim serviceUrl As String = "https://mydomain.com/api/sales"
            Dim input As Object = New With { _
                            .APIKey = "b7f3ac51f3a9c-043ed53-4453e0-873-2c151f0cf", _
                            .Status = "Tony Stark", _
                            .TotalAmount = "150.50", _
                            .CustomerID = "CO12345", _
    .SalesDate = "2020-04-41 14:24:58" } Dim inputJson As String = (New JavaScriptSerializer()).Serialize(input) Dim httpRequest As HttpWebRequest = DirectCast(WebRequest.Create(New Uri(serviceUrl)), HttpWebRequest) httpRequest.Accept = "application/json" httpRequest.ContentType = "application/json" httpRequest.Method = "POST" Dim bytes As Byte() = Encoding.UTF8.GetBytes(inputJson) Using stream As Stream = httpRequest.GetRequestStream() stream.Write(bytes, 0, bytes.Length) stream.Close() End Using Using httpResponse As HttpWebResponse = DirectCast(httpRequest.GetResponse(), HttpWebResponse) Using stream As Stream = httpResponse.GetResponseStream() Me.lbl_result.Text = (New StreamReader(stream)).ReadToEnd() End Using End Using End Function






    Thursday, July 30, 2020 10:13 AM

Answers

  • User1686398519 posted

    Hi kengkit,

    According to your needs, I modified the code you provided, you can refer to it.

            Dim input As Object = New With {
                Key .APIKey = "b7f3ac51f3a9c-043ed53-4453e0-873-2c151f0cf",
                Key .Status = "Tony Stark",
                Key .TotalAmount = "150.50",
                Key .CustomerID = "CO12345",
                Key .SalesDate = "2020-04-41 14:24:58",
                Key .OrderList = New List(Of Object) From {
                    New With {Key .OrderType = "Parcel", Key .OrderAmount = "50.50", Key .OrderStatus = "Confirmed"},
                    New With {Key .OrderType = "Gift", Key .VoucherCode = "WEE12345", Key .OrderAmount = "100.00", Key .OrderStatus = "Confirmed"}
                }
            }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 31, 2020 5:56 AM

All replies

  • User1120430333 posted

    The Json must travel in a known class/object/type between the WebAPI client and WebAPI service using encapsulation.

    https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)

    <end>

    In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components.<sup id="cite_ref-Rogers01_1-0" class="reference">[1]</sup> Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called "getters" and "setters") to access the values, and other client classes call these methods to retrieve and modify the values within the object.

    <end>

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

    https://www.codeproject.com/articles/1050468/data-transfer-object-design-pattern-in-csharp

    https://www.c-sharpcorner.com/UploadFile/pranayamr/generate-class-from-json-xml-in-visual-studio/

    So you have to maker a List(of T) for the DTO you're going to send from the WebAPI client to WebApi Service

    ASP.NET MVC Webclient calls to WebAPI service using the DTO pattern to send and receive data.  There is no List<of T> DTO(s) being passed on a post. But hopefully, you should be able to understand how to do it. You should be able to find examples using Bing or Google. The DTO is created in a classlib project called Entities and the ASP.NET MVC  client and the WebAPI service projects have reference to Entities classlib project  and know about the DTO.

    Service

    Imports System.Web.Http
    Imports DAL
    Imports Entities
    
    Namespace Controllers
    
        <CustomExceptionFilter>
        Public Class ProjectController
            Inherits ApiController
    
            Private ReadOnly _daoproject As IDaoProject
    
            public sub New (daoproject As IDaoProject)
                _daoproject = daoproject
            End sub
    
            <HttpGet>
            <ActionName("GetProjectById")>
            public Function GetProjectById(ByVal id As Int32) As DtoProject
                return _daoproject.GetProjectById(id)
            End Function
    
    
            <HttpGet>
            <ActionName("GetProjectsByUserId")>
            public Function GetProjectsByUserId(ByVal userid As String) As List(Of DtoProject)
                return _daoproject.GetProjectsByUserId(userid)
            End Function
    
            <HttpPost>
            <ActionName("CreateProject")>
            public sub CreateProject(ByVal dto As DtoProject)
                Call _daoproject.CreateProject(dto)
            End sub
            
            <HttpPost>
            <ActionName("UpdateProject")>
            public sub UpdateProject(ByVal dto As DtoProject)
                Call _daoproject.UpdateProject(dto)
            End sub
    
            <HttpPost>
            <ActionName("DeleteProject")>
            public sub  DeleteProject(ByVal dto As DtoId)
                Call _daoproject.DeleteProject(dto.Id)
            End sub
            
        End Class
    End Namespace
    ===========================================================================
    
    Imports System.Web.Http
    Imports DAL
    Imports Entities
    
    Namespace Controllers
    
        <CustomExceptionFilter>
        Public Class TaskController
            Inherits ApiController
    
            Private ReadOnly _daotask As IDaoTask
    
            public sub New (daotask As IDaoTask)
                _daotask = daotask
            End sub
    
            <HttpGet>
            <ActionName("GetTaskById")>
            public Function  GetTaskById(ByVal id As int32) as DtoTask
                return _daotask.GetTaskById(id)
            End Function
            
            <HttpGet>
            <ActionName("GetTasksByProjectId")>
            public  Function GetTasksByProjectId(byval id as int32) as List(Of DtoTask)
                return _daotask.GetTasksByProjectId(id)
            End Function
    
            <HttpPost>
            <ActionName("CreateTask")>
            public sub  CreateTask(ByVal dto As DtoTask)
                Call _daotask.CreateTask(dto)
            End sub
           
            <HttpPost>
            <ActionName("UpdateTask")>
            public sub  UpdateTask(ByVal dto As DtoTask)
                Call _daotask.UpdateTask(dto)
            End sub
            
            <HttpPost>
            <ActionName("DeleteTask")>
            public sub  DeleteTask(byval dto As DtoId)
                Call _daotask.DeleteTask(dto.Id)
            End sub
            
        End Class
    End Namespace
    

    MVC Client....

    Imports System.Net
    Imports Entities
    Imports Newtonsoft.Json
    
    Namespace WebApi
        Public Class WebApi
            Implements IWebApi
    
            #Region "Project"
            public Function  GetProjsByUserIdApi(userid As String) as List(of DtoProject) Implements IWebApi.GetProjsByUserIdApi
    
                dim dtoprojects = new List(Of DtoProject)
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectsByUserId?userid=" & userid
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim projects = JsonConvert.DeserializeObject(of List(Of DtoProject))(json)
                    dtoprojects = projects
                End Using
    
                Return dtoprojects
    
            End Function
           
            public Function GetProjByIdApi(id As int32) as DtoProject Implements IWebApi.GetProjByIdApi
    
                dim dto as DtoProject
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectById?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim project = JsonConvert.DeserializeObject(of DtoProject)(json)
                    dto = project
                End Using
               
                Return dto
    
            End Function
    
            public sub CreateProjectApi(dto As DtoProject) Implements IWebApi.CreateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/CreateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
                
            End sub
            
            public sub UpdateProjectApi(dto As DtoProject) Implements IWebApi.UpdateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/UpdateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
    
            public sub DeleteProjectApi(dto As DtoId) Implements IWebApi.DeleteProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/DeleteProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
            #End Region
    
            #Region "Task"
    
            public function GetTasksByProjIdApi(id as int32) as List(Of DtoTask) Implements IWebApi.GetTasksByProjIdApi
    
                Dim dtotasks = new List(Of DtoTask)
    
                dim url = "http://localhost/WebApiVB/api/task/GetTasksByProjectId?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim tasks = JsonConvert.DeserializeObject(of List(Of DtoTask))(json)
                    dtotasks = tasks
                End Using
    
                Return dtotasks
    
            End function
            
            public Function  GetTaskByIdApi(id As int32) As DtoTask Implements IWebApi.GetTaskByIdApi
    
                dim dto as DtoTask
    
                dim url = "http://localhost/WebApiVB/api/task/GetTaskById?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim task = JsonConvert.DeserializeObject(of DtoTask)(json)
                    dto = task
                End Using
    
                return dto
    
            End Function
    
            public sub CreateTaskApi(dto As DtoTask) Implements IWebApi.CreateTaskApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/task/CreateTask"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
              
            End sub
            
            public sub UpdateTaskApi(dto As DtoTask) Implements IWebApi.UpdateTaskApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/task/UpdateTask"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
                
            End sub
            
            public sub DeleteTaskApi(dto As DtoId) Implements IWebApi.DeleteTaskApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/task/DeleteTask"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
            #End Region  
            
            #Region "Cache"
    
            public Function  GetCacheApi() As DtoCache Implements IWebApi.GetCacheApi
    
                dim dtocache = new DtoCache()
    
                dim url = "http://localhost/WebApiVB/api/cache/GetCache"
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim deserialized = JsonConvert.DeserializeObject(of DtoCacheRoot)(json)
    
                    dtocache.ProjectTypes = deserialized.DtoCache.ProjectTypes
                    dtocache.Durations = deserialized.DtoCache.Durations
                    dtocache.Statuses = deserialized.DtoCache.Statuses
                    dtocache.Resources = deserialized.DtoCache.Resources
    
                End Using
    
                return dtocache
    
            End Function
            #End Region
    
        End Class
    End Namespace
    

    Public Class DtoProject
    
        Public Property ProjectId As Int32
        Public Property ClientName As String
        Public Property ProjectName As String
        Public Property Technology As String
        Public Property ProjectType As String
        Public Property UserId As String
        Public Property StartDate  As DateTime
        Public Property EndDate As DateTime? 
        Public Property Cost As Decimal
       
    End Class
    
    ===============================================
    ublic Class DtoTask
    
        Public Property TaskId As Int32
        Public Property TaskName As String
        Public Property Note As String
        Public Property StartDate  As DateTime
        Public Property EndDate As Nullable(of DateTime) 
        Public Property ResourceId As String
        Public Property ProjectId As Int32
        Public Property TaskDuration As String
        Public Property TaskSpent As String
        Public Property Status As String
    
    End Class

    Thursday, July 30, 2020 4:09 PM
  • User1686398519 posted

    Hi kengkit,

    According to your needs, I modified the code you provided, you can refer to it.

            Dim input As Object = New With {
                Key .APIKey = "b7f3ac51f3a9c-043ed53-4453e0-873-2c151f0cf",
                Key .Status = "Tony Stark",
                Key .TotalAmount = "150.50",
                Key .CustomerID = "CO12345",
                Key .SalesDate = "2020-04-41 14:24:58",
                Key .OrderList = New List(Of Object) From {
                    New With {Key .OrderType = "Parcel", Key .OrderAmount = "50.50", Key .OrderStatus = "Confirmed"},
                    New With {Key .OrderType = "Gift", Key .VoucherCode = "WEE12345", Key .OrderAmount = "100.00", Key .OrderStatus = "Confirmed"}
                }
            }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 31, 2020 5:56 AM
  • User944339287 posted
    Tq. May i know what program you are using for this demonstration? Tq
    Friday, July 31, 2020 7:57 AM
  • User944339287 posted

    Hi YiHuiSun,

    I having an error while trying to apply your suggestion.

    'OrderType' is not a member of '<anonymous type>'; it doe not exist in the current context.

            Dim serviceUrl As String = "https://mydomain.com/api/sales"
            Dim input As Object = New With { _
                            .APIKey = "b7f3ac51f3a9c-043ed53-4453e0-873-2c151f0cf", _
                            .Status = "Tony Stark", _
                            .TotalAmount = "150.50", _
                            .CustomerID = "CO12345", _
                            .SalesDate = "2020-04-41 14:24:58", _
                            .TransactionList = New List(Of Object) From { _
                                .OrderType = "Parcel", _
                                .OrderAmount = "50.00", _
                                .OrderStatus = "Confirmed" _
                            }
            }
    
            Dim inputJson As String = (New JavaScriptSerializer()).Serialize(input)



    Saturday, August 1, 2020 4:54 AM
  • User944339287 posted

    problem solved when i added New With after FROM

    Sunday, August 2, 2020 4:11 PM