ePezhman
ePezhman

Reputation: 4010

Post a value from HttpPost Android to Asp.Net Web Api

I need to post some value from my Android app to my Asp.Net Web Api. but I only get null in my Web Api, where do you think my problem is?

I have this code for android :

in MainActivity:

List<NameValuePair> IdsToSend = new ArrayList<NameValuePair>();
for (Message item : messages) {
    IdsToSend.add(new BasicNameValuePair("messageIds", item.Id));               
}
parser.sendPostRequest(UpdateMessageStatuseURL ,IdsToSend);

in some other file:

public void sendPostRequest(String url, List<NameValuePair> params) {

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            httpClient.execute(httpPost);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

and my Web Api:

public void Post([FromBody]int[] messageIds)
        {
            var dc = new SMSDataDataContext();
            foreach (var item in messageIds)
            {
                var message = dc.Messages.SingleOrDefault(x => x.Id == item);
                if (message != null)
                {
                    message.Statuse = 1;
                    dc.SubmitChanges();
                }
            }

        }

Upvotes: 0

Views: 1465

Answers (1)

You would be better of binding to a complex type.

public class YourModel
{
    public int[] messageIds { get; set; }
}

public void Post(YourModel model) { ... }

That will work. If for whatever reason, you cannot have a complex type, you will need to ensure the request message body is like this.

=1&=2&=3&=30

It might be wierd but this will bind to int[]. I do not know how you can submit this payload from Android but there must be a way. Easier way out will probably be using a complex type. BTW, FromBody will be needed only for simple types.

Upvotes: 2

Related Questions