Table of Contents

Class ApiTyped

Namespace
Custom.Hybrid
Assembly
ToSic.Sxc.Dnn.WebApi.dll

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
object
ApiController
DnnApiController
DnnSxcControllerRoot
DnnSxcControllerBase
DnnSxcCustomControllerBase
ApiTyped
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

insightsGroup string

Name 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

ITypedStack

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

ITypedStack

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

IAppTyped

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

ServiceKit16

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

ICodeLog

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

ICmsContext

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:

  1. If it's a simple view, then this will just contain streams with the main Item(s) and Header
  2. If the view expects no data, it will just contain a Default stream containing no items
  3. If the view has a Query behind it, then MyData will have all the streams provided by the Query
public IBlockInstance MyData { get; }

Property Value

IBlockInstance

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

ITypedItem

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

ITypedItem

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

IEnumerable<ITypedItem>

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

ITypedModel

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

ICmsPage

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

ICmsUser

MyView

View-information such as the view Name, Identity or Edition.

public ICmsView MyView { get; }

Property Value

ICmsView

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

string

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 AcceptedResult 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.

AsEntity(ICanBeEntity)

Unwraps a dynamic entity or ITypedItem back into the underlying IEntity

public IEntity AsEntity(ICanBeEntity thing)

Parameters

thing ICanBeEntity

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

data object

An original object which can be converted to a TypedItem, such as a IEntity .

noParamOrder NoParamOrder

see Convention: Named Parameters

propsRequired bool?

make the resulting object strict, default true

mock bool?

Specify that the data is fake/mock data, which should pretend to be an Item. Default is false

Returns

ITypedItem

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

list object

The original list which is usually a list of IEntity objects.

noParamOrder NoParamOrder

see Convention: Named Parameters

propsRequired bool?

make the resulting object strict, default true

Returns

IEnumerable<ITypedItem>

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, ITypedItemWrapper16, ITypedItem, new()

Parameters

source object

the source object - a List/Enumerable of IEntity or ITypedItem

protector NoParamOrder

see Convention: Named Parameters

nullIfNull bool

if true will return null when source is null - otherwise a wrapper item with empty-contents

Returns

IEnumerable<T>

Type Parameters

T

the 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

items object[]

objects to stack together

Returns

ITypedStack

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, ITypedItemWrapper16, ITypedItem, new()

Parameters

items object[]

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

original object
noParamOrder NoParamOrder

see Convention: Named Parameters

propsRequired bool?

make the resulting object strict, default true

Returns

ITyped

AsTypedList(object, NoParamOrder, bool?)

Create a list

public IEnumerable<ITyped> AsTypedList(object list, NoParamOrder noParamOrder = default, bool? propsRequired = null)

Parameters

list object

List/Enumerable object containing a bunch of items to make typed

noParamOrder NoParamOrder

see Convention: Named Parameters

propsRequired bool?

make the resulting object strict, default true

Returns

IEnumerable<ITyped>

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, ITypedItemWrapper16, ITypedItem, new()

Parameters

source object

the source object - an IEntity or ITypedItem

protector NoParamOrder

see Convention: Named Parameters

mock bool

if true will return a fake when source is null - otherwise a wrapper item with empty-contents

Returns

T

Type Parameters

T

the 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 BadRequestResult 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.

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 ConflictResult 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.

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

error object

Contains errors to be returned to the client.

Returns

HttpResponseMessage

The created .net-core like ConflictObjectResult 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.

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

noParamOrder NoParamOrder

see Convention: Named Parameters

download bool?

If a download should be enforced (otherwise the file may just be displayed - like an image)

virtualPath string

Path in the website to get the file from. Provide either virtualPath or contents

contentType string

Mime Content-type. Will try to auto-detect from virtualPath or fileDownloadName if not provided.

fileDownloadName string

Download name. If provided, it will try to force download/save on the browser.

contents object

Content 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 ForbidResult 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.

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

path string

The path, like Helper.cs, ./helper.cs, ../../Helper.cs or /SomeFolderInApp/Helper.cs (new 16.05)

noParamOrder NoParamOrder

see Convention: Named Parameters

className string

Optional class name, if it doesn't match the file name (new 16.03)

Returns

dynamic

,

Remarks

  • Created in 16.02
  • className added 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

TService

Interface (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 NoContentResult object 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 NotFoundResult 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(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

value object

Returns

HttpResponseMessage

The created .net-core like NotFoundObjectResult 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.

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 OkResult 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.

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

value object

The content value to format in the entity body.

Returns

HttpResponseMessage

The created .net-core like OkObjectResult 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.

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

url string

The URL to redirect to.

Returns

RedirectResult

The created .net-core like RedirectResult 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.

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

url string

The URL to redirect to.

Returns

HttpResponseMessage

The created .net-core like RedirectResult 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.

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

noParamOrder NoParamOrder

see Convention: Named Parameters

stream Stream

the stream

fileName string

file name to save to

contentType string

content-type of the target item (important for security checks)

guid Guid?
field string
subFolder string

Returns

IFile

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

statusCode int

The status code to set on the response.

Returns

HttpResponseMessage

The created .net-core like StatusCodeResult object 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

statusCode int

The status code to set on the response.

value object

The value to set on the .net-core like `ObjectResult"/>.

Returns

HttpResponseMessage

The created .net-core like ObjectResult object 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 UnauthorizedResult 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(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

value object

Returns

HttpResponseMessage

The created .net-core like UnauthorizedObjectResult 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.