Sam Afshari's Notes
  • GitHub
  • Twitter/X
  • All posts
  • Ed
  • NuGets
  • POIWorld
  • RedCorners

REST requests with Xamarin and RestSharp - Fri, Jul 8, 2016

RestSharp (available on NuGet) is a clean way to send HTTP requests and handle their response. As a portable package, you can use it in your Xamarin.iOS and Xamarin.Android applications. The following example, POSTs a serialized JSON body, created automatically from a C# class, to an endpoint located at https://myserver.com/api/messages/message. It also sends a token parameter inside the query string:

public class MessageDTO : DTO
{
    public string Sender { get; set; }
    public string Recipient { get; set; }
    public string Body { get; set; }
}
public static class PinHelper
{
    async void SendMessage(MessageDTO dto)
    {
        const string ApiPath = "https://myserver.com/api/";
        var client = new RestClient (ApiPath);
        var request = new RestRequest ("messages/message", Method.POST);
        request.AddQueryParameter ("token", Settings.Token);
        request.AddJsonBody (dto);

        try
        {
            var result = await client.ExecuteTaskAsync(request);
            Debug.WriteLine($"Result Status Code: {result.StatusCode} - {result.Content}");
        }
        catch (Exception e) {
            Debug.WriteLine ($"Error: {e.Message}");
        }
    }
}

On an ASP.NET WebApi controller with EntityFramework, this request can be received and stored using a function that looks like this:

[HttpPost][Route("message")]
public IHTTPActionResult AddMessage(string token, [FromBody] MessageDTO dto)
{
    Message message = new Message ();
    dto.Inject (message);
    db.Messages.Add (message);
    db.SaveChanges ();

    return Ok ();
}

Back to Home


© Sam Afshari 2024