简体   繁体   中英

pass list type of class as parameter in HttpWebRequest to consume Web API

I have Web API developed in framework 4 and code is as below

[HttpPost]
        public string ValidateData(List<MsrValidateData> data)
        {
            return _repository.ValidateAllData(data);
        }

Now I want to consume this in asp.net web form server side How do i consume with HttpWebRequest to post list type of data

I am using like this

System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
        req.ContentType = "application/json";
        req.Method = "POST";

But how do I pass list type of data as parameter to request?

Your haven't shared structure of your class MsrValidateData so i am using field1 and field2 for its fields. Please replace field1 & field2 with your actual fields of class MsrValidateData and add data to your request as shown below:

    System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
    req.ContentType = "application/json";
    req.Method = "POST";
    string postData = @"
        {
            'Data':
            [
                { 'field1': 'value11', 'field2': 'value12' },
                { 'field1': 'value11', 'field2': 'value12' },
                { 'field1': 'value11', 'field2': 'value12' }
            ]
        }";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    req.ContentLength = byteArray.Length;
    System.IO.Stream dataStream = req.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

Create a new class ListMsrValidateData:

public class ListMsrValidateData
{
    public List<MsrValidateData> Data { get; set; }
}

Modify your ValidateData method as below:

    [HttpPost]
    public string ValidateData([FromBody] ListMsrValidateData data)
    {
        return _repository.ValidateAllData(data);
    }

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