Skip to content

Web Services development

pablocar80 edited this page Jun 21, 2020 · 2 revisions

Web Services are created by:

  • implementing the interface IWebService.
  • decorating the class with the LaraWebService attribute.

Classes decorated with the LaraWebService attribute published with the method LaraUI.PublishAssemblies(). Alternatively, you can use Lara.Publish(...) to pick individual classes to publish.

Example of a JSON web service that receives X and Y in the request's body, and returns X+Y:

using System.Net;
using System.Runtime.Serialization;
using System.Threading.Tasks;

namespace Integrative.Lara.Samples
{
    [DataContract]
    class MyRequest
    {
        [DataMember]
        public int X { get; set; }

        [DataMember]
        public int Y { get; set; }
    }

    [DataContract]
    class MyResponse
    {
        [DataMember]
        public int Total { get; set; }
    }

    [LaraWebService(Address = "/myWS",
        ContentType = "application/json", Method = "GET")]
    class MyWebService : IWebService
    {
        public Task<string> Execute()
        {
            // RequestBody is a string with the request's body
            var text = LaraUI.Service.RequestBody;

            // Parse: replies HTTP bad request if parse fails
            var request = LaraUI.JSON.Parse<MyRequest>(text);

            // create response
            var response = new MyResponse
            {
                Total = request.X + request.Y
            };

            // return response as JSON string
            var json = LaraUI.JSON.Stringify(response);
            return Task.FromResult(json);
        }
    }
}