Class ApiTyped
Base class for v16 Typed WebAPI files. Use it to create custom WebAPI endpoints in your App.
It provides the ServiceKit16 on property Kit which contains all the popular services to create amazing stuff.
[PublicApi]
[JsonFormatter]
public abstract class ApiTyped : DnnSxcCustomControllerBase, IHasLog
- Inheritance
-
objectApiControllerDnnApiControllerDnnSxcControllerRootDnnSxcControllerBaseDnnSxcCustomControllerBaseApiTyped
- Implements
Remarks
Important: This is very different from Razor12 or Razor14, as it doesn't rely on dynamic code.
Be aware of this since the APIs are very different - see Typed Code.
Constructors
ApiTyped()
Main constructor. Doesn't have parameters so it can easily be inherited.
protected ApiTyped()
ApiTyped(string)
Alternate constructor to use when inheriting, placing the Insights logs in an own section.
protected ApiTyped(string insightsGroup)
Parameters
insightsGroupstringName of the section in Insights
Properties
AllResources
Stack of all Resources in the System, merging Resources of View, App, Site, Global etc. Will retrieve values by priority, with View-Resources being top priority and Preset-Resources being the lowest.
Tip
If you know that Resources come from the App, you should prefer App.Resources instead.
That is faster and helps people reading your code figure out where to change a value.
public ITypedStack AllResources { get; }
Property Value
AllSettings
Stack of all Settings in the System, merging Settings of View, App, Site, Global etc. Will retrieve values by priority, with View-Settings being top priority and Preset-Settings being the lowest.
Tip
If you know that Settings come from the App, you should prefer App.Settings instead.
That is faster and helps people reading your code figure out where to change a value.
public ITypedStack AllSettings { get; }
Property Value
App
The current App object (with strictly typed Settings/Resources).
Use it to access App properties such as Path or any data in the App.
public IAppTyped App { get; }
Property Value
Kit
The Service Kit containing all kinds of services which are commonly used. The services on the Kit are context-aware, so they know what App is currently being used etc.
public ServiceKit16 Kit { get; }
Property Value
Link
Link helper object to create the correct links
public ILinkService Link { get; }
Property Value
- ILinkService
A ILinkService object.
Log
The logger for the current Razor / WebApi which allows you to add logs to Insights.
public ICodeLog Log { get; }
Property Value
MyContext
This Context tells you about the environment, such as
- the current User
- the Page
- the View
- the Site
It's supposed to replace direct access to Dnn or Oqtane object in Razor and WebAPI code, allowing hybrid code that works everywhere.
public ICmsContext MyContext { get; }
Property Value
Remarks
New in v11.11
MyData
All the data which the current Template received, based on the View configuration. There are a few common scenarios:
- If it's a simple view, then this will just contain streams with the main Item(s) and Header
- If the view expects no data, it will just contain a
Defaultstream containing no items - If the view has a Query behind it, then MyData will have all the streams provided by the Query
public IDataSource MyData { get; }
Property Value
MyHeader
The Header-Item belonging to this Template/Module. This data is edited by the user directly on this specific module. In some cases it can also be a pre-set item configured in the View to be used if the user has not added any data himself.
public ITypedItem MyHeader { get; }
Property Value
MyItem
The main Item belonging to this Template/Module. This data is edited by the user directly on this specific module. In some cases it can also be a pre-set item configured in the View to be used if the user has not added any data himself.
If this view can have a list of items (more than one) then this contains the first item. To get all the items, see ToSic.Sxc.Code.Internal.IDynamicCode16.MyItems
public ITypedItem MyItem { get; }
Property Value
MyItems
List of all Items belonging to this Template/Module. This data is edited by the user directly on this specific module. In some cases it can also be a pre-set item configured in the View to be used if the user has not added any data himself.
If this view is configured to only have one item, then this list will only contain one item. Otherwise, it will have as many items as the editor added.
public IEnumerable<ITypedItem> MyItems { get; }
Property Value
MyModel
Data passed to this Razor template by a caller.
This is typical for Razor components which are re-used, and called from other Razor templates using @Html.Partial("filename.cshtml", new { thing = 7 }).
public ITypedModel MyModel { get; }
Property Value
MyPage
Information about the current Page (called Tab in DNN). It's especially useful to get current URL Parameters.
public ICmsPage MyPage { get; }
Property Value
MyUser
Information about the current user. It's especially useful to see if the user has any kind of Admin privileges.
public ICmsUser MyUser { get; }
Property Value
MyView
View-information such as the view Name, Identity or Edition.
public ICmsView MyView { get; }
Property Value
Remarks
New in v12.02
UniqueKey
A unique, random key for the current module. It's recommended for giving DOM elements a unique id for scripts to then access them.
It's generated for every content-block, and more reliable than Module.Id
since that sometimes results in duplicate keys, if the many blocks are used inside each other.
It's generated using a GUID and converted/shortened. In the current version it's 8 characters long, so it has 10^14 combinations, making collisions extremely unlikely. (currently 8 characters)
Tip
To get a unique key which is based on additional objects such as Entities, use the UniqueKeyWith(params object[]) method.
public string UniqueKey { get; }
Property Value
Remarks
If you get a fresh IKeyService it will also create a new UniqueKey.
So your code should usually use the built-in property UniqueKey which comes from the shared ServiceKit Key.
Methods
Accepted()
Creates a .net-core like AcceptedResult object that produces an .net-core like StatusCodes.Status202Accepted response.
Typical use: return Accepted();
[NonAction]
public HttpResponseMessage Accepted()
Returns
- HttpResponseMessage
The created .net-core like
AcceptedResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
AsEntity(ICanBeEntity)
Unwraps a dynamic entity or ITypedItem back into the underlying IEntity
public IEntity AsEntity(ICanBeEntity thing)
Parameters
thingICanBeEntity
Returns
- IEntity
A normal IEntity
AsItem(object, NoParamOrder, bool?, bool?)
Convert something to a ITypedItem. This works for all kinds of IEntitys, IDynamicEntitys as well as Lists/IEnumerables of those.
Will always return a single item. If a list is provided, it will return the first item in the list. If null was provided, it will return null.
public ITypedItem AsItem(object data, NoParamOrder noParamOrder = default, bool? propsRequired = null, bool? mock = null)
Parameters
dataobjectAn original object which can be converted to a TypedItem, such as a IEntity .
noParamOrderNoParamOrderpropsRequiredbool?make the resulting object strict, default
truemockbool?Specify that the data is fake/mock data, which should pretend to be an Item. Default is
false
Returns
Remarks
New in v16.02
AsItems(object, NoParamOrder, bool?)
Convert an object containing a list of Entities or similar to a list of ITypedItems.
public IEnumerable<ITypedItem> AsItems(object list, NoParamOrder noParamOrder = default, bool? propsRequired = null)
Parameters
listobjectThe original list which is usually a list of IEntity objects.
noParamOrderNoParamOrderpropsRequiredbool?make the resulting object strict, default
true
Returns
Remarks
New in v16.01
AsList<T>(object, NoParamOrder, bool)
Convert a list of Entities or TypedItems into a strongly typed list.
Typically, the type will be from your AppCode.Data.
public IEnumerable<T> AsList<T>(object source, NoParamOrder protector = default, bool nullIfNull = false) where T : class, ICanWrapData
Parameters
sourceobjectthe source object - a List/Enumerable of
IEntityorITypedItemprotectorNoParamOrdernullIfNullboolif
truewill return null whensourceisnull- otherwise a wrapper item with empty-contents
Returns
- IEnumerable<T>
Type Parameters
Tthe target type
Remarks
Release in v17.05
AsStack(params object[])
Create a typed object which will provide all the properties of the things wrapped inside it. The priority is first-object first, so if multiple items have the property, the first in the list will be returned.
public ITypedStack AsStack(params object[] items)
Parameters
itemsobject[]objects to stack together
Returns
AsStack<T>(params object[])
Create a custom-typed object which will provide all the properties of the things wrapped inside it. The priority is first-object first, so if multiple items have the property, the first in the list will be returned.
public T AsStack<T>(params object[] items) where T : class, ICanWrapData, new()
Parameters
itemsobject[]objects to stack together
Returns
- T
Item of the custom type
Type Parameters
T
Remarks
New in 17.07
AsTyped(object, NoParamOrder, bool?)
Creates a typed object to read the original passed into this function. This is usually used to process objects which the compiler can't know, such as anonymous objects returned from helper code etc.
If you have an array of such objects, use AsTypedList(object, NoParamOrder, bool?).
public ITyped AsTyped(object original, NoParamOrder noParamOrder = default, bool? propsRequired = null)
Parameters
originalobjectnoParamOrderNoParamOrderpropsRequiredbool?make the resulting object strict, default
true
Returns
AsTypedList(object, NoParamOrder, bool?)
Create a list
public IEnumerable<ITyped> AsTypedList(object list, NoParamOrder noParamOrder = default, bool? propsRequired = null)
Parameters
listobjectList/Enumerable object containing a bunch of items to make typed
noParamOrderNoParamOrderpropsRequiredbool?make the resulting object strict, default
true
Returns
As<T>(object, NoParamOrder, bool)
Convert an Entity or TypedItem into a strongly typed object.
Typically, the type will be from your AppCode.Data.
public T As<T>(object source, NoParamOrder protector = default, bool mock = false) where T : class, ICanWrapData
Parameters
sourceobjectthe source object - an
IEntityorITypedItemprotectorNoParamOrdermockboolif
truewill return a fake whensourceisnull- otherwise a wrapper item with empty-contents
Returns
- T
Type Parameters
Tthe target type
Remarks
Released v17.05
BadRequest()
Creates an .net-core like BadRequestResult that produces a .net-core like StatusCodes.Status400BadRequest response.
Typical use: return BadRequest();
[NonAction]
public BadRequestResult BadRequest()
Returns
- BadRequestResult
The created .net-core like
BadRequestResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Conflict()
Creates an .net-core like ConflictResult that produces a .net-core like StatusCodes.Status409Conflict response.
Typical use: return Conflict();
[NonAction]
public ConflictResult Conflict()
Returns
- ConflictResult
The created .net-core like
ConflictResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Conflict(object)
Creates an .net-core like ConflictObjectResult that produces a .net-core like StatusCodes.Status409Conflict response.
Typical use: return Conflict("the stored file is newer");
[NonAction]
public HttpResponseMessage Conflict(object error)
Parameters
errorobjectContains errors to be returned to the client.
Returns
- HttpResponseMessage
The created .net-core like
ConflictObjectResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
File(NoParamOrder, bool?, string, string, string, object)
Create a File-result to stream to the client
Typical use: return File(download: true, contentType: "text/xml", contents: ...);
public dynamic File(NoParamOrder noParamOrder = default, bool? download = null, string virtualPath = null, string contentType = null, string fileDownloadName = null, object contents = null)
Parameters
noParamOrderNoParamOrderdownloadbool?If a download should be enforced (otherwise the file may just be displayed - like an image)
virtualPathstringPath in the website to get the file from. Provide either virtualPath or contents
contentTypestringMime Content-type. Will try to auto-detect from virtualPath or fileDownloadName if not provided.
fileDownloadNamestringDownload name. If provided, it will try to force download/save on the browser.
contentsobjectContent of the result - a string, byte[] or stream to include.
Returns
- dynamic
Remarks
Added in 2sxc 12.05
Forbid()
Creates a .net-core like ForbidResult (.net-core like StatusCodes.Status403Forbidden by default).
Typical use: return Forbid();
[NonAction]
public HttpResponseMessage Forbid()
Returns
- HttpResponseMessage
The created .net-core like
ForbidResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Some authentication schemes, such as cookies, will convert .net-core like StatusCodes.Status403Forbidden to
a redirect to show a login page.
GetCode(string, NoParamOrder, string)
Create an instance of a class in a .cs code file.
Note that the class name in the file must match the file name, so MyHelpers.cs must have a MyHelpers class.
public dynamic GetCode(string path, NoParamOrder noParamOrder = default, string className = null)
Parameters
pathstringThe path, like
Helper.cs,./helper.cs,../../Helper.csor/SomeFolderInApp/Helper.cs(new 16.05)noParamOrderNoParamOrderclassNamestringOptional class name, if it doesn't match the file name (new 16.03)
Returns
- dynamic
,
Remarks
- Created in 16.02
classNameadded in 16.03- Ability to give a path beginning with
/as app-root in 16.05
In older code there was a similar CreateInstance method
GetService<TService>()
Get a service from the Dependency Injection. The service can come from 2sxc, EAV or the underlying platform (Dnn, Oqtane).
public TService GetService<TService>() where TService : class
Returns
- TService
An object of the type or interface requested, or null if not found in the DI.
Type Parameters
TServiceInterface (preferred) or Class which is needed
NoContent()
Creates a .net-core like NoContentResult object that produces an empty
.net-core like StatusCodes.Status204NoContent response.
Typical use: return NoContent();
[NonAction]
public HttpResponseMessage NoContent()
Returns
- HttpResponseMessage
The created .net-core like
NoContentResultobject for the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
NotFound()
Creates an .net-core like NotFoundResult that produces a .net-core like StatusCodes.Status404NotFound response.
Typical use: return NotFound();
[NonAction]
public NotFoundResult NotFound()
Returns
- NotFoundResult
The created .net-core like
NotFoundResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
NotFound(object)
Creates an .net-core like NotFoundObjectResult that produces a .net-core like StatusCodes.Status404NotFound response.
Typical use: return Unauthorized("try another ID");
[NonAction]
public HttpResponseMessage NotFound(object value)
Parameters
valueobject
Returns
- HttpResponseMessage
The created .net-core like
NotFoundObjectResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Ok()
Creates a .net-core like OkResult object that produces an empty .net-core like StatusCodes.Status200OK response.
Typical use: return Ok();
[NonAction]
public OkResult Ok()
Returns
- OkResult
The created .net-core like
OkResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Ok(object)
Creates an .net-core like OkObjectResult object that produces an .net-core like StatusCodes.Status200OK response.
Typical use: return Ok(objectToInclude);
[NonAction]
public HttpResponseMessage Ok(object value)
Parameters
valueobjectThe content value to format in the entity body.
Returns
- HttpResponseMessage
The created .net-core like
OkObjectResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Redirect(string)
Creates a .net-core like RedirectResult object that redirects (.net-core like StatusCodes.Status302Found)
to the specified url.
Typical use: return Redirect("https://2sxc.org");
[NonAction]
public RedirectResult Redirect(string url)
Parameters
urlstringThe URL to redirect to.
Returns
- RedirectResult
The created .net-core like
RedirectResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
RedirectPermanent(string)
Creates a .net-core like RedirectResult object with .net-core like RedirectResult.Permanent set to true
(.net-core like StatusCodes.Status301MovedPermanently) using the specified url.
Typical use: return RedirectPermanent("https://2sxc.org");
[NonAction]
public HttpResponseMessage RedirectPermanent(string url)
Parameters
urlstringThe URL to redirect to.
Returns
- HttpResponseMessage
The created .net-core like
RedirectResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
SaveInAdam(NoParamOrder, Stream, string, string, Guid?, string, string)
Save a file from a stream (usually an upload from the browser) into an adam-field of an item. Read more about this in the WebAPI docs for SaveInAdam
public IFile SaveInAdam(NoParamOrder noParamOrder = default, Stream stream = null, string fileName = null, string contentType = null, Guid? guid = null, string field = null, string subFolder = "")
Parameters
noParamOrderNoParamOrderstreamStreamthe stream
fileNamestringfile name to save to
contentTypestringcontent-type of the target item (important for security checks)
guidGuid?fieldstringsubFolderstring
Returns
StatusCode(int)
Creates a .net-core like StatusCodeResult object by specifying a statusCode.
Typical use: return StatusCode(403);
[NonAction]
public HttpResponseMessage StatusCode(int statusCode)
Parameters
statusCodeintThe status code to set on the response.
Returns
- HttpResponseMessage
The created .net-core like
StatusCodeResultobject for the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
StatusCode(int, object)
Creates a .net-core like ObjectResult object by specifying a statusCode and value
Typical use: return StatusCode(304, "not modified");
[NonAction]
public HttpResponseMessage StatusCode(int statusCode, object value)
Parameters
statusCodeintThe status code to set on the response.
valueobjectThe value to set on the .net-core like `ObjectResult"/>.
Returns
- HttpResponseMessage
The created .net-core like
ObjectResultobject for the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Unauthorized()
Creates an .net-core like UnauthorizedResult that produces an .net-core like StatusCodes.Status401Unauthorized response.
Typical use: return Unauthorized();
[NonAction]
public HttpResponseMessage Unauthorized()
Returns
- HttpResponseMessage
The created .net-core like
UnauthorizedResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.
Unauthorized(object)
Creates an .net-core like UnauthorizedObjectResult that produces a .net-core like StatusCodes.Status401Unauthorized response.
Typical use: return Unauthorized("we don't like this");
[NonAction]
public HttpResponseMessage Unauthorized(object value)
Parameters
valueobject
Returns
- HttpResponseMessage
The created .net-core like
UnauthorizedObjectResultfor the response.
Remarks
This is a shim to ensure that .net Framework code can be written the same way as .net core WebApis.
It returns a dynamic to make it easy to use, but the real .net core implementation returns a typed object.