The mechanism above also works in WebApi Controllers (if you have 2sxc 10.01+). Note that specifically in WebApi you can only use GetCode(...)
for .cs
files.
-
-
-
⬇️ Result | Source ➡️
Click to see the result of a WebApi call with the shared code:
@inherits Custom.Hybrid.RazorTyped
@using ToSic.Razor.Blade
<p>
Click to see the result of a WebApi call with the shared code:
<button type="button" class="btn btn-primary" onclick="callApiWithSharedCode(this)">
Call WebApi
</button>
</p>
<script>
function callApiWithSharedCode(context) {
$2sxc(context).webApi.fetchJson('app/auto/api/sharedcode/hello')
.then(function (results) {
console.log(results);
alert(results);
});
return false;
}
</script>
Source Code of SharedCodeController.cs
// 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
[ValidateAntiForgeryToken] // protects API from users not on your site (CSRF protection)
public class SharedCodeController : Custom.Hybrid.Api14 // see https://r.2sxc.org/CustomWebApi
{
[HttpGet]
[AllowAnonymous]
public string Hello()
{
var shared = CreateInstance("../shared/FunctionsBasic.cs");
return shared.SayHello();
}
}
// The next line is for 2sxc-internal quality checks, you can ignore this
// 2sxclint:disable:no-dnn-namespaces - 2sxclint:disable:no-web-namespace
Source Code of FunctionsBasic.cs
// Important notes:
// - This class should have the same name as the file it's in
public class FunctionsBasic {
public string SayHello() {
return "Hello from shared functions!";
}
}
// Example for another class in the same file
public class Second {
public string SayHello() {
return "Hello from the second class!";
}
}