繁体   English   中英

从 razor 模板调用外部 API

[英]Calling an external API from razor template

我正在尝试在我的 2sxc razor 模板中使用 MS Dynamics API JSON 响应作为数据源。 出于安全原因,我想将查询生成为服务器端发布请求。 我的代码必须位于 razor 模板中,因为我没有 FTP 访问权限来上传自定义代码或库。

我一直在尝试在自定义应用程序中使用的标准异步请求。

  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);

        }

当我在 2sxc razor 页面中尝试时,我收到错误


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. 

我知道可能有一种更性感的方式来做到这一点,但我正在画一个空白。

谢谢!

好的,所以我想我找到了一种可行的方法。 我用这个转储了异步:

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);
}

        
        
}

似乎适用于我正在使用的小型数据集。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM