0

I am using RestSharp on Xamarin to communicate with WebAPI using POST. I can send something and get a response but the outcome wasn't what I expected.

This is my code on Xamarin.

                var request = new RestSharp.RestRequest ("api/device/stats", RestSharp.Method.POST);
            request.AddHeader ("Content-Type", "application/json; charset=utf-8");

            request.RequestFormat = DataFormat.Json;
            request.AddBody(new AppUsageInfo {MAC = "ASDF"}); 
            RestSharp.IRestResponse response = client.Execute (request);
            var content = response.Content;

On my WebAPI :

 public string Post([FromUri]UsageLogModel usageState)
    {
        //LogFunction.AddUsageLogs(usageState);
        if (usageState.MAC == null)
            return "fail";
        else
            return "success";
    }

UsageLogModel is :

public class UsageLogModel
{
    public string MAC;
}

Somehow the response is "Fail" which MAC is null. I scratched my head but have no idea what is going on.-

1
  • The type used in rest request AppUsageInfois different from the one you're expecting in you post method UsageLogModel Commented Apr 29, 2016 at 12:11

1 Answer 1

2

Your Xamarin code is putting the MAC content in the body of the request (which is probably appropriate for a POST), but the Web API is expected the parameter to be in the query string (that's what the [FromUri] attribute is doing). Try changing the Web API method to:

public string Post([FromBody]UsageLogModel usageState)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.