1

I'm trying to use a MS Dynamics API JSON response as a datasource in my 2sxc razor template. For security reasons I want to generate the query as a server side post request. My code has to live inside of the razor template as I have no FTP access to upload custom code or libraries.

I've tried the standard async request which I use in custom apps all the time.

  private static readonly HttpClient client = new HttpClient();


        protected void Page_Load(object sender, EventArgs e)
        {
            GetData();
        }


        public async void GetData() {

            var requestparams = new Dictionary<string, string>
            {
                { "key", "123456789" },
                { "Operation", "GetEntityTypes" }
            };

            var content = new FormUrlEncodedContent(requestparams);

            var response = await client.PostAsync("https://api.someserver.com/", content);

            var responseString = await response.Content.ReadAsStringAsync();

            Response.Write(responseString);

        }

When I try it inside a 2sxc razor page page I get the error


Error: System.InvalidOperationException: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. 

I know there is probably a sexier way to do this but I'm drawing a blank.

Thanks!

1 Answers1

1

Ok so I think I figured out a method that works. I dumped the asynch using this:

private static readonly HttpClient client = new HttpClient();

       public string GetEntities(string entity, string attributes, string apiurl, string key)
        {

            var requestparams = new Dictionary<string, string>
            {
                { "key", key },
                { "Operation", "GetEntities" },
                { "Entity", entity },
                { "Attributes",attributes}
            };

            var content = new FormUrlEncodedContent(requestparams);
            var task = System.Threading.Tasks.Task.Run(() => client.PostAsync(apiurl, content));
            task.Wait();
            var result = task.Result;
            var response = result.Content.ReadAsStringAsync().Result;
            return (response);
}

        
        
}

Seems to work well for the small data set I'm using.