Skip to main content

WebApi Tutorials

Tutorial Home

Very basic WebApi Examples

In this example, we'll assume your WebApi controller is called Basic (so the file is called BasicController.cs and has a class called BasicController). It's located in /api which is the default location for WebApi controllers.
We'll show various usages both with the new webApi.fetchJson(...) and webApi.fetch(...) standard fetch

  1. with the new webApi.fetchJson(...) and webApi.fetch(...) commands (new in v12.10)
  2. with the browser built in fetch
  3. using jQuery (not recommended any more, because we believe jQuery is dying)
  4. another example calling the endpoint using a parameter to calculate something so you can see how to use url parameters.

Click to see the result of a WebApi call with the shared code:


<button type="button" class="btn btn-primary" onclick="helloFetchJson(this)">Quick Fetch Json "Hello"</button>
<script>
  // Fetch using modern Browser Fetch-promises, with auto-get Json
  // This is the recommended method if you expect JSON, because it's simpler
  // This also uses the shortest API syntax `controller/method`
  function helloFetchJson(moduleContext) {
    $2sxc(moduleContext).webApi.fetchJson('basic/hello')
      .then(data => alert('Result using quick Fetch JSON: ' + data));
  }
</script>

  <button type="button" class="btn btn-primary" onclick="helloFetch(this)">Quick Fetch "Hello"</button> 
  
  <script>
    // Fetch using modern Browser APIs
    // This is the more manual method, in case you don't expect JSON or want more control
    // This uses the full internal syntax `app/auto/api/controller/method`
    function helloFetch(moduleContext) {
      $2sxc(moduleContext).webApi.fetch('app/auto/api/basic/hello')
        .then(response => response.json())
        .then(data => alert('Result using quick Fetch: ' + data));
    }
  </script>

  <button type="button" class="btn btn-primary" onclick="helloFetchManual(this)">Quick Fetch "Hello"</button>
  
  <script>
    // Manual Fetch call using more code
    // This is the most manual method, but shows how it actually works internally
    function helloFetchManual(moduleContext) {
      var moduleApi = $2sxc(moduleContext).webApi;  // webApi for this specific Module
      var fullApiUrl = moduleApi.url('app/auto/api/basic/hello'); // API url based on current App
      var headers = moduleApi.headers("GET");       // Headers used for GET calls
      fetch(fullApiUrl, { headers: { ...headers } })
          .then(response => response.json())
          .then(data => alert('Result using manual Fetch: ' + data));
    }
  </script>

  <button type="button" class="btn btn-secondary" onclick="helloJQuery(this)">jQuery Get Hello</button>
  
  <script>
    // jQuery versions (not recommended any more, will not work on pages without jQuery)
    function helloJQuery(moduleContext) {
      $2sxc(moduleContext).webApi.get('app/auto/api/basic/hello')
        .then(function (results) {
          alert("Result using jQuery: " + results);      
        });
    }
  </script>

  <button type="button" class="btn btn-primary" onclick="squareFetch(this, 7)">Fetch Square 7</button>
  <button type="button" class="btn btn-primary" onclick="squareFetch(this, 27)">Fetch Square 27</button>
  
  <script>
    function squareFetch(moduleContext, original) {
      $2sxc(moduleContext).webApi.fetchJson('basic/square?number=' + original)
        .then(data => alert('The square of ' + original + '= ' + data));
    }
</script>

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
@{
  // Tell the page that we need the 2sxc Js APIs
  Kit.Page.Activate("2sxc.JsCore"); 
}
<!-- unimportant stuff, hidden -->

Very basic WebApi Examples In this... <!-- unimportant stuff, hidden -->

<button type="button" class="btn btn-primary" onclick="helloFetchJson(this)">Quick Fetch Json "Hello"</button>
<script>
  // Fetch using modern Browser Fetch-promises, with auto-get Json
  // This is the recommended method if you expect JSON, because it's simpler
  // This also uses the shortest API syntax `controller/method`
  function helloFetchJson(moduleContext) {
    $2sxc(moduleContext).webApi.fetchJson('basic/hello')
      .then(data => alert('Result using quick Fetch JSON: ' + data));
  }
</script>



  <button type="button" class="btn btn-primary" onclick="helloFetch(this)">Quick Fetch "Hello"</button> 
  
  <script>
    // Fetch using modern Browser APIs
    // This is the more manual method, in case you don't expect JSON or want more control
    // This uses the full internal syntax `app/auto/api/controller/method`
    function helloFetch(moduleContext) {
      $2sxc(moduleContext).webApi.fetch('app/auto/api/basic/hello')
        .then(response => response.json())
        .then(data => alert('Result using quick Fetch: ' + data));
    }
  </script>


  <button type="button" class="btn btn-primary" onclick="helloFetchManual(this)">Quick Fetch "Hello"</button>
  
  <script>
    // Manual Fetch call using more code
    // This is the most manual method, but shows how it actually works internally
    function helloFetchManual(moduleContext) {
      var moduleApi = $2sxc(moduleContext).webApi;  // webApi for this specific Module
      var fullApiUrl = moduleApi.url('app/auto/api/basic/hello'); // API url based on current App
      var headers = moduleApi.headers("GET");       // Headers used for GET calls
      fetch(fullApiUrl, { headers: { ...headers } })
          .then(response => response.json())
          .then(data => alert('Result using manual Fetch: ' + data));
    }
  </script>


  <button type="button" class="btn btn-secondary" onclick="helloJQuery(this)">jQuery Get Hello</button>
  
  <script>
    // jQuery versions (not recommended any more, will not work on pages without jQuery)
    function helloJQuery(moduleContext) {
      $2sxc(moduleContext).webApi.get('app/auto/api/basic/hello')
        .then(function (results) {
          alert("Result using jQuery: " + results);      
        });
    }
  </script>


  <button type="button" class="btn btn-primary" onclick="squareFetch(this, 7)">Fetch Square 7</button>
  <button type="button" class="btn btn-primary" onclick="squareFetch(this, 27)">Fetch Square 27</button>
  
  <script>
    function squareFetch(moduleContext, original) {
      $2sxc(moduleContext).webApi.fetchJson('basic/square?number=' + original)
        .then(data => alert('The square of ' + original + '= ' + data));
    }
</script>


<!-- unimportant stuff, hidden -->

Source Code of /api/BasicController.cs

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

// Add namespaces for security check in Oqtane & DNN despite differences in .net core/.net Framework
// If you only target one platform, you can remove the parts you don't need
#if NETCOREAPP
using Microsoft.AspNetCore.Authorization; // .net core [AllowAnonymous] & [Authorize]
using Microsoft.AspNetCore.Mvc;           // .net core [HttpGet] / [HttpPost] etc.
#else
using System.Web.Http;                    // .net 4.5 [AllowAnonymous] / [HttpGet]
using DotNetNuke.Web.Api;                 // [DnnModuleAuthorize] & [ValidateAntiForgeryToken]
#endif

[AllowAnonymous]                          // all commands can be accessed without a login
public class BasicController : Custom.Hybrid.Api14 // see https://r.2sxc.org/CustomWebApi
{
  [HttpGet]                               // [HttpGet] says we're listening to GET requests
  public string Hello()
  {
    return "Hello from the basic controller in /api";
  }

  [HttpGet]				// [HttpGet] says we're listening to GET requests
  public int Square(int number)
  {
    return number * number;
  }

}

// The next line is for 2sxc-internal quality checks, you can ignore this
// 2sxclint:disable:no-dnn-namespaces - 2sxclint:disable:no-web-namespace