'Calling a function from a C# API controller with Axios

I have function in a C# controller file that makes an API call to fetch some placeholder data that is hard coded locally.

[Route("api/ReportingCenter/GetReportList")]
[HttpGet]
public class ReportController : ApiController
{
   public async Task<IHttpActionResult> GetReportList(CancellationToken cancellationToken)
   {
       using (var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
                       HttpContext.Current.Response.ClientDisconnectedToken))
       {
           var userId = 11;
           var projId = 22;
           using (var reportDb = new ReportDb(userId, projId))
           {
               var list = reportDb.GetReports(userId, projId);
               return Json(list);
           }
       }
    }
}

public class ReportDb : PortalDb
{
    public List<ReportInfo> GetReports(int userid, int projectid)
    {
        var ReportList = new List<ReportInfo>();
        ReportList.Add(new ReportInfo(1,"file1.pdf", 11, "a file with data in it", 11112222,"pdf", 1, "22"));

    }
}

I coded a button and a function with an aspx file that should make an axios call to run the GetReportList function from the controller. When the button is click, nothing happens. Any suggestions on how to make it so that the API call is made when the button is clicked in the aspx file?

<asp:Content ID="Content5" ContentPlaceHolderID="primaryContent" runat="server">
    <div id="reporting-app-container">
        <input type="button" value="ReportInfo" class="btn btn-sm btn primary" 
        onclick="getReportInfo"/>
    </div>

    <script src="/ReportsModule/app/dist/reporting-app-bundle.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            window.ReportingApp();
        });

        async function getReportInfo(id) {
            console.log("pre-axios call")
            const response = await axios.get("api/ReportingCenter/GetReportList")
                .then(function (response) {
                    // handle success
                    console.log(response);
                })
                .catch(function (error) {
                    // handle error
                    console.log(error);
                });
        }
    </script>
</asp:Content>


Solution 1:[1]

.then and .catch are methods of a Promise, which is what you'd get if you called axios.get without awaiting it. A Promise represents an action which you've started in the background, which may or may not have finished yet, and which can call callback functions supplied by you if/when it completes successfully or throws an error. Or at least that's a very short description of what it is.

To pass your callback functions to the Promise returned by axios.get, remove the async and await, a bit like this:

function getReportInfo(id) {
  axios.get('api/ReportingCenter/GetReportList')
    .then(function (response) {
      // handle success
      console.log(response);
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
    .then(function () {
      // always executed
    });
}

If you want response to be the actual response from the API, rather than a Promise to give you the actual response once the web request has completed, then you can await the Promise, a bit like this:

async function getReportInfo(id) {
  try {
    const response = await axios.get('api/ReportingCenter/GetReportList');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

A note of caution if you choose the second option - are you sure all your users' browsers support ECMAScript 2017? If not then the await / async approach probably isn't a good idea and you should stick with the first option.

Code snippets are adapted from this bit of the axios API documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1