Class Endpoint<TRequest, TResponse>
use this base class for defining endpoints that use both request and response dtos.
Inheritance
Inherited Members
Namespace: FastEndpoints
Assembly: FastEndpoints.dll
Syntax
public abstract class Endpoint<TRequest, TResponse> : BaseEndpoint, IEndpoint, IEventBus, IServiceResolverBase where TRequest : notnull
Type Parameters
Name | Description |
---|---|
TRequest | the type of the request dto |
TResponse | the type of the response dto |
Properties
BaseURL
the base url of the current request
Declaration
public string BaseURL { get; }
Property Value
Type | Description |
---|---|
string |
Config
gives access to the configuration. if you need to access this property from within the endpoint Configure() method, make sure to pass in the config
to .AddFastEndpoints(config: builder.Configuration)
Declaration
public IConfiguration Config { get; }
Property Value
Type | Description |
---|---|
IConfiguration |
Env
gives access to the hosting environment
Declaration
public IWebHostEnvironment Env { get; }
Property Value
Type | Description |
---|---|
IWebHostEnvironment |
Files
the files sent with the request. only populated when content-type is 'multipart/form-data'
Declaration
public IFormFileCollection Files { get; }
Property Value
Type | Description |
---|---|
IFormFileCollection |
Form
the form sent with the request. only populated if content-type is 'application/x-www-form-urlencoded' or 'multipart/form-data'
Declaration
public IFormCollection Form { get; }
Property Value
Type | Description |
---|---|
IFormCollection |
HttpMethod
the http method of the current request
Declaration
public Http HttpMethod { get; }
Property Value
Type | Description |
---|---|
Http |
Logger
the logger for the current endpoint type
Declaration
public ILogger Logger { get; }
Property Value
Type | Description |
---|---|
ILogger |
Response
the response that is sent to the client.
Declaration
public TResponse Response { get; set; }
Property Value
Type | Description |
---|---|
TResponse |
ResponseStarted
get or set whether the response has started. you'd only use this if you're writing to the response stream by yourself.
Declaration
public bool ResponseStarted { get; set; }
Property Value
Type | Description |
---|---|
bool |
User
the current user principal
Declaration
public ClaimsPrincipal User { get; }
Property Value
Type | Description |
---|---|
ClaimsPrincipal |
ValidationFailed
indicates if there are any validation failures for the current request
Declaration
public bool ValidationFailed { get; }
Property Value
Type | Description |
---|---|
bool |
Methods
AccessControl(string, Apply?, params string[])
if the 'FastEndpoints.Generator' package is used, calling this method will generate a static class called '{assembly-name}.Auth.Allow'
with a const field with this keyName
that has a 3 digit auto generated value (permission code). doesn't do anything without the
source
generator package installed.
Declaration
protected void AccessControl(string keyName, Apply? behavior = null, params string[] groupNames)
Parameters
Type | Name | Description |
---|---|---|
string | keyName | the name of the constant field to generate |
Apply? | behavior | specify whether to add the generated permission code as a permission requirement for this endpoint.
this does the same thing as calling "Permissions(...)" method.
i.e. if this optional argument is set to ToThisEndpoint, then a user principal must posses this permission code
in order to be allowed access to this endpoint. you don't need to explicitly specify it via a |
string[] | groupNames | optionally specify one or more groups (sets of permissions) this |
AccessControl(string, params string[])
if the 'FastEndpoints.Generator' package is used, calling this method will generate a static class called '{assembly-name}.Auth.Allow'
with a const field with this keyName
that has a 3 digit auto generated value (permission code). doesn't do anything without the
source
generator package installed.
Declaration
protected void AccessControl(string keyName, params string[] groupNames)
Parameters
Type | Name | Description |
---|---|---|
string | keyName | the name of the constant field to generate |
string[] | groupNames | optionally specify one or more groups (sets of permissions) this |
AddError(ValidationFailure)
add a FluentValidation.Results.ValidationFailure to the current collection of validation failures of the endpoint
Declaration
public void AddError(ValidationFailure failure)
Parameters
Type | Name | Description |
---|---|---|
ValidationFailure | failure | the validation failure to add |
AddError(Expression<Func<TRequest, object?>>, string, string?, Severity)
adds an error message for the specified property of the request dto
Declaration
public void AddError(Expression<Func<TRequest, object?>> property, string errorMessage, string? errorCode = null, Severity severity = Severity.Error)
Parameters
Type | Name | Description |
---|---|---|
Expression<Func<TRequest, object>> | property | the property to add the error message for |
string | errorMessage | the error message |
string | errorCode | the error code associated with the error |
Severity | severity | the severity of the error |
AddError(string, string?, Severity)
adds a "GeneralError" to the current list of validation failures
Declaration
public void AddError(string message, string? errorCode = null, Severity severity = Severity.Error)
Parameters
Type | Name | Description |
---|---|---|
string | message | the error message |
string | errorCode | the error code associated with the error |
Severity | severity | the severity of the error |
AllowAnonymous(params Http[])
allow unauthenticated requests to this endpoint. optionally specify a set of verbs to allow unauthenticated access with. i.e. if the endpoint is listening to POST, PUT & PATCH and you specify AllowAnonymous(Http.POST), then only PUT & PATCH will require authentication.
Declaration
protected void AllowAnonymous(params Http[] verbs)
Parameters
Type | Name | Description |
---|---|---|
Http[] | verbs |
AllowAnonymous(string[])
allow unauthenticated requests to this endpoint for a specified set of http verbs. i.e. if the endpoint is listening to POST, PUT & PATCH and you specify AllowAnonymous(Http.POST), then only PUT & PATCH will require authentication.
Declaration
protected void AllowAnonymous(string[] verbs)
Parameters
Type | Name | Description |
---|---|---|
string[] | verbs |
AllowFileUploads(bool)
enable file uploads with multipart/form-data content type
Declaration
protected void AllowFileUploads(bool dontAutoBindFormData = false)
Parameters
Type | Name | Description |
---|---|---|
bool | dontAutoBindFormData | set 'true' to disable auto binding of form data which enables uploading and reading of large files without buffering to memory/disk. you can access the multipart sections for reading via the FormFileSectionsAsync() method. |
AllowFormData(bool)
enable form-data submissions
Declaration
protected void AllowFormData(bool urlEncoded = false)
Parameters
Type | Name | Description |
---|---|---|
bool | urlEncoded | set to true to accept |
AuthSchemes(params string[])
specify which authentication schemes to use for authenticating requests to this endpoint
Declaration
protected void AuthSchemes(params string[] authSchemeNames)
Parameters
Type | Name | Description |
---|---|---|
string[] | authSchemeNames | the authentication scheme names |
Claims(params string[])
allows access if the claims principal has ANY of the given claim types
Declaration
protected void Claims(params string[] claimTypes)
Parameters
Type | Name | Description |
---|---|---|
string[] | claimTypes | the claim types |
ClaimsAll(params string[])
allows access if the claims principal has ALL of the given claim types
Declaration
protected void ClaimsAll(params string[] claimTypes)
Parameters
Type | Name | Description |
---|---|---|
string[] | claimTypes | the claim types |
CreateScope()
if you'd like to resolve scoped or transient services from the MS DI container, obtain a service scope from this method and dispose the scope when the work is complete.
using var scope = CreateScope();
var scopedService = scope.Resolve<MyService>();
Declaration
public IServiceScope CreateScope()
Returns
Type | Description |
---|---|
IServiceScope |
CreateTokenWith<TService>(string, Action<UserPrivileges>)
create the access/refresh token pair response with a given refresh-token service.
Declaration
protected Task<TResponse> CreateTokenWith<TService>(string userId, Action<UserPrivileges> userPrivileges) where TService : IRefreshTokenService<TResponse>
Parameters
Type | Name | Description |
---|---|---|
string | userId | the id of the user for which the tokens will be generated for |
Action<UserPrivileges> | userPrivileges | the user priviledges to be embeded in the jwt such as roles/claims/permissions |
Returns
Type | Description |
---|---|
Task<TResponse> |
Type Parameters
Name | Description |
---|---|
TService | the type of the token service |
Delete(string, Expression<Func<TRequest, object>>)
specify a DELETE route pattern using a replacement expression.
Declaration
protected void Delete(string routePattern, Expression<Func<TRequest, object>> members)
Parameters
Type | Name | Description |
---|---|---|
string | routePattern | the words prefixed with @ will be replaced by property names of the
|
Expression<Func<TRequest, object>> | members |
|
Delete(params string[])
specify to listen for DELETE requests on one or more routes.
Declaration
protected void Delete(params string[] routePatterns)
Parameters
Type | Name | Description |
---|---|---|
string[] | routePatterns |
Description(Action<RouteHandlerBuilder>, bool)
describe openapi metadata for this endpoint. optionaly specify whether or not you want to clear the default Accepts/Produces metadata.
EXAMPLE: b => b.Accepts<Request>("text/plain")
Declaration
protected void Description(Action<RouteHandlerBuilder> builder, bool clearDefaults = false)
Parameters
Type | Name | Description |
---|---|---|
Action<RouteHandlerBuilder> | builder | the route handler builder for this endpoint |
bool | clearDefaults | set to true if the defaults should be cleared |
DontAutoTag()
if swagger auto tagging based on path segment is enabled, calling this method will prevent a tag from being added to this endpoint.
Declaration
protected void DontAutoTag()
DontCatchExceptions()
use this only if you have your own exception catching middleware. if this method is called in config, an automatic error response will not be sent to the client by the library. all exceptions will be thrown and it would be the responsibility of your exeception catching middleware to handle them.
Declaration
protected void DontCatchExceptions()
DontThrowIfValidationFails()
disable auto validation failure responses (400 bad request with error details) for this endpoint.
HINT: this only applies to request dto validation.
Declaration
protected void DontThrowIfValidationFails()
EnableAntiforgery()
enables antiforgery token verification for this endpoint
Declaration
protected void EnableAntiforgery()
ExecuteAsync(TRequest, CancellationToken)
the handler method for the endpoint that returns the response dto. this method is called for each request received.
Declaration
public virtual Task<TResponse> ExecuteAsync(TRequest req, CancellationToken ct)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
CancellationToken | ct | a cancellation token |
Returns
Type | Description |
---|---|
Task<TResponse> |
FormFileSectionsAsync(CancellationToken)
gets a stream of nullable FileMultipartSections from the incoming multipart/form-data without buffering the whole file to memory/disk as done with IFormFile
Declaration
protected IAsyncEnumerable<FileMultipartSection?> FormFileSectionsAsync(CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellation | optional cancellation token |
Returns
Type | Description |
---|---|
IAsyncEnumerable<FileMultipartSection> |
Get(string, Expression<Func<TRequest, object>>)
specify a GET route pattern using a replacement expression.
Declaration
protected void Get(string routePattern, Expression<Func<TRequest, object>> members)
Parameters
Type | Name | Description |
---|---|---|
string | routePattern | the words prefixed with @ will be replaced by property names of the
|
Expression<Func<TRequest, object>> | members |
|
Get(params string[])
specify to listen for GET requests on one or more routes.
Declaration
protected void Get(params string[] routePatterns)
Parameters
Type | Name | Description |
---|---|---|
string[] | routePatterns |
Group<TEndpointGroup>()
if this endpoint is part of an endpoint group, specify the type of the Group concrete class where the common configuration for the group is specified.
WARNING: this method can only be called after the endpoint route has been specified.
Declaration
protected override sealed void Group<TEndpointGroup>() where TEndpointGroup : Group, new()
Type Parameters
Name | Description |
---|---|
TEndpointGroup | the type of your Group concrete class |
Overrides
Exceptions
Type | Condition |
---|---|
InvalidOperationException | thrown if endpoint route hasn't yet been specified |
HandleAsync(TRequest, CancellationToken)
the handler method for the endpoint. this method is called for each request received.
Declaration
public virtual Task HandleAsync(TRequest req, CancellationToken ct)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
CancellationToken | ct | a cancellation token |
Returns
Type | Description |
---|---|
Task |
Head(string, Expression<Func<TRequest, object>>)
specify a HEAD route pattern using a replacement expression.
Declaration
protected void Head(string routePattern, Expression<Func<TRequest, object>> members)
Parameters
Type | Name | Description |
---|---|---|
string | routePattern | the words prefixed with @ will be replaced by property names of the
|
Expression<Func<TRequest, object>> | members |
|
Head(params string[])
specify to listen for HEAD requests on one or more routes.
Declaration
protected void Head(params string[] routePatterns)
Parameters
Type | Name | Description |
---|---|---|
string[] | routePatterns |
OnAfterHandle(TRequest, TResponse)
override this method if you'd like to do something after the handler is executed.
Declaration
public virtual void OnAfterHandle(TRequest req, TResponse res)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
TResponse | res | the response dto that was sent to the client |
OnAfterHandleAsync(TRequest, TResponse, CancellationToken)
override this method if you'd like to do something after the handler is executed.
Declaration
public virtual Task OnAfterHandleAsync(TRequest req, TResponse res, CancellationToken ct)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
TResponse | res | the response dto that was sent to the client |
CancellationToken | ct | a cancellation token |
Returns
Type | Description |
---|---|
Task |
OnAfterValidate(TRequest)
override this method if you'd like to do something to the request dto after it gets validated.
Declaration
public virtual void OnAfterValidate(TRequest req)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
OnAfterValidateAsync(TRequest, CancellationToken)
override this method if you'd like to do something to the request dto after it gets validated.
Declaration
public virtual Task OnAfterValidateAsync(TRequest req, CancellationToken ct)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
CancellationToken | ct | a cancellation token |
Returns
Type | Description |
---|---|
Task |
OnBeforeHandle(TRequest)
override this method if you'd like to do something to the request dto before the handler is executed.
Declaration
public virtual void OnBeforeHandle(TRequest req)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
OnBeforeHandleAsync(TRequest, CancellationToken)
override this method if you'd like to do something to the request dto before the handler is executed.
Declaration
public virtual Task OnBeforeHandleAsync(TRequest req, CancellationToken ct)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
CancellationToken | ct | a cancellation token |
Returns
Type | Description |
---|---|
Task |
OnBeforeValidate(TRequest)
override this method if you'd like to do something to the request dto before it gets validated.
Declaration
public virtual void OnBeforeValidate(TRequest req)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
OnBeforeValidateAsync(TRequest, CancellationToken)
override this method if you'd like to do something to the request dto before it gets validated.
Declaration
public virtual Task OnBeforeValidateAsync(TRequest req, CancellationToken ct)
Parameters
Type | Name | Description |
---|---|---|
TRequest | req | the request dto |
CancellationToken | ct | a cancellation token |
Returns
Type | Description |
---|---|
Task |
OnValidationFailed()
override this method if you'd like to do something when a validation failure occurs.
Declaration
public virtual void OnValidationFailed()
OnValidationFailedAsync(CancellationToken)
override this method if you'd like to do something when a validation failure occurs.
Declaration
public virtual Task OnValidationFailedAsync(CancellationToken ct)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | ct | a cancellation token |
Returns
Type | Description |
---|---|
Task |
Options(Action<RouteHandlerBuilder>)
set endpoint configurations options using an endpoint builder action ///
Declaration
protected void Options(Action<RouteHandlerBuilder> builder)
Parameters
Type | Name | Description |
---|---|---|
Action<RouteHandlerBuilder> | builder | the builder for this endpoint |
Patch(string, Expression<Func<TRequest, object>>)
specify a PATCH route pattern using a replacement expression.
Declaration
protected void Patch(string routePattern, Expression<Func<TRequest, object>> members)
Parameters
Type | Name | Description |
---|---|---|
string | routePattern | the words prefixed with @ will be replaced by property names of the
|
Expression<Func<TRequest, object>> | members |
|
Patch(params string[])
specify to listen for PATCH requests on one or more routes.
Declaration
protected void Patch(params string[] routePatterns)
Parameters
Type | Name | Description |
---|---|---|
string[] | routePatterns |
Permissions(params string[])
allows access if the claims principal has ANY of the given permissions
Declaration
protected void Permissions(params string[] permissions)
Parameters
Type | Name | Description |
---|---|---|
string[] | permissions | the permissions |
PermissionsAll(params string[])
allows access if the claims principal has ALL of the given permissions
Declaration
protected void PermissionsAll(params string[] permissions)
Parameters
Type | Name | Description |
---|---|---|
string[] | permissions | the permissions |
Policies(params string[])
specify one or more authorization policy names you have added to the middleware pipeline during app startup/ service configuration that should be applied to this endpoint.
Declaration
protected void Policies(params string[] policyNames)
Parameters
Type | Name | Description |
---|---|---|
string[] | policyNames | one or more policy names (must have been added to the pipeline on startup) |
Policy(Action<AuthorizationPolicyBuilder>)
specify an action for building an authorization requirement which applies only to this endpoint.
Declaration
protected void Policy(Action<AuthorizationPolicyBuilder> policy)
Parameters
Type | Name | Description |
---|---|---|
Action<AuthorizationPolicyBuilder> | policy | the policy builder action |
Post(string, Expression<Func<TRequest, object>>)
specify a POST route pattern using a replacement expression.
Declaration
protected void Post(string routePattern, Expression<Func<TRequest, object>> members)
Parameters
Type | Name | Description |
---|---|---|
string | routePattern | the words prefixed with @ will be replaced by property names of the
|
Expression<Func<TRequest, object>> | members |
|
Post(params string[])
specify to listen for POST requests on one or more routes.
Declaration
protected void Post(params string[] routePatterns)
Parameters
Type | Name | Description |
---|---|---|
string[] | routePatterns |
PostProcessor<TPostProcessor>()
configure a post-processor to be executed after the main handler function is done. call this method multiple times to add multiple post-processors. processors are executed in the order they are configured in the endpoint.
Declaration
protected void PostProcessor<TPostProcessor>() where TPostProcessor : class, IPostProcessor<TRequest, TResponse>
Type Parameters
Name | Description |
---|---|
TPostProcessor | the post-processor to add |
PostProcessors(params IPostProcessor<TRequest, TResponse>[])
configure a collection of post-processors to be executed after the main handler function is done. processors are executed in the order they are defined here.
Declaration
protected void PostProcessors(params IPostProcessor<TRequest, TResponse>[] postProcessors)
Parameters
Type | Name | Description |
---|---|---|
IPostProcessor<TRequest, TResponse>[] | postProcessors | the post processors to be executed |
PreProcessor<TPreProcessor>()
configure a pre-processor to be executed before the main handler function is called. call this method multiple times to add multiple pre-processors. processors are executed in the order they are configured in the endpoint.
Declaration
protected void PreProcessor<TPreProcessor>() where TPreProcessor : class, IPreProcessor<TRequest>
Type Parameters
Name | Description |
---|---|
TPreProcessor | the pre-processor to add |
PreProcessors(params IPreProcessor<TRequest>[])
configure a collection of pre-processors to be executed before the main handler function is called. processors are executed in the order they are defined here.
Declaration
protected void PreProcessors(params IPreProcessor<TRequest>[] preProcessors)
Parameters
Type | Name | Description |
---|---|---|
IPreProcessor<TRequest>[] | preProcessors | the pre processors to be executed |
ProcessorState<TState>()
retrieve the common processor state for this endpoint.
Declaration
public TState ProcessorState<TState>() where TState : class, new()
Returns
Type | Description |
---|---|
TState |
Type Parameters
Name | Description |
---|---|
TState | the type of the processor state |
Exceptions
Type | Condition |
---|---|
InvalidOperationException | thrown if the requested type of the processor state does not match with what's already stored in the context |
PublishAsync<TEvent>(TEvent, Mode, CancellationToken)
publishes a given event model to all subscribers registered to handle the that type of event.
Declaration
public Task PublishAsync<TEvent>(TEvent eventModel, Mode waitMode = Mode.WaitForAll, CancellationToken cancellation = default) where TEvent : notnull
Parameters
Type | Name | Description |
---|---|---|
TEvent | eventModel | the notification event model/dto to publish |
Mode | waitMode | specify whether to wait for none, any or all of the subscribers to complete their work |
CancellationToken | cancellation | an optional cancellation token |
Returns
Type | Description |
---|---|
Task | a Task that matches the wait mode specified. WaitForNone returns an already completed Task (fire and forget). WaitForAny returns a Task that will complete when any of the subscribers complete their work. WaitForAll return a Task that will complete only when all of the subscribers complete their work. |
Type Parameters
Name | Description |
---|---|
TEvent | the type of the event model |
Put(string, Expression<Func<TRequest, object>>)
specify a PUT route pattern using a replacement expression.
Declaration
protected void Put(string routePattern, Expression<Func<TRequest, object>> members)
Parameters
Type | Name | Description |
---|---|---|
string | routePattern | the words prefixed with @ will be replaced by property names of the
|
Expression<Func<TRequest, object>> | members |
|
Put(params string[])
specify to listen for PUT requests on one or more routes.
Declaration
protected void Put(params string[] routePatterns)
Parameters
Type | Name | Description |
---|---|---|
string[] | routePatterns |
Query<T>(string, bool)
get the value of a given query parameter by specifying the resulting type and query parameter name. NOTE: an automatic validation error is sent to the client when value retrieval is not successful.
Declaration
protected T? Query<T>(string paramName, bool isRequired = true)
Parameters
Type | Name | Description |
---|---|---|
string | paramName | query parameter name |
bool | isRequired | set to false for disabling the automatic validation error |
Returns
Type | Description |
---|---|
T | the value if retrieval is successful or null if |
Type Parameters
Name | Description |
---|---|
T | type of the result |
RequestBinder(IRequestBinder<TRequest>)
configure custom model binding for this endpoint by supplying an IRequestBinder implementation. by calling this method, you're completely bypassing the built-in model binding and taking things into your own hands for this endpoint.
Declaration
protected void RequestBinder(IRequestBinder<TRequest> binder)
Parameters
Type | Name | Description |
---|---|---|
IRequestBinder<TRequest> | binder | custom model binder implementation to use for this endpoint |
Resolve(Type)
resolve an instance for the given type from the dependency injection container. will throw if unresolvable.
Declaration
public object Resolve(Type typeOfService)
Parameters
Type | Name | Description |
---|---|---|
Type | typeOfService | the type of the service to resolve |
Returns
Type | Description |
---|---|
object |
Exceptions
Type | Condition |
---|---|
InvalidOperationException | Thrown if requested service cannot be resolved |
Resolve<TService>()
resolve an instance for the given type from the dependency injection container. will throw if unresolvable.
Declaration
public TService Resolve<TService>() where TService : class
Returns
Type | Description |
---|---|
TService |
Type Parameters
Name | Description |
---|---|
TService | the type of the service to resolve |
Exceptions
Type | Condition |
---|---|
InvalidOperationException | Thrown if requested service cannot be resolved |
ResponseCache(int, ResponseCacheLocation, bool, string?, string[]?)
specify response caching settings for this endpoint
Declaration
protected void ResponseCache(int durationSeconds, ResponseCacheLocation location = ResponseCacheLocation.Any, bool noStore = false, string? varyByHeader = null, string[]? varyByQueryKeys = null)
Parameters
Type | Name | Description |
---|---|---|
int | durationSeconds | the duration in seconds for which the response is cached |
ResponseCacheLocation | location | the location where the data from a particular URL must be cached |
bool | noStore | specify whether the data should be stored or not |
string | varyByHeader | the value for the Vary response header |
string[] | varyByQueryKeys | the query keys to vary by |
ResponseInterceptor(IResponseInterceptor)
configure a response interceptor to be called before the SendAsync response is sent to the browser. this will override any globally configured interceptor. if you return a response to the browser, then the rest of the SendAsync method will be skipped.
Declaration
protected void ResponseInterceptor(IResponseInterceptor responseInterceptor)
Parameters
Type | Name | Description |
---|---|---|
IResponseInterceptor | responseInterceptor | the response interceptor to be executed |
Roles(params string[])
allows access if the claims principal has ANY of the given roles
Declaration
protected void Roles(params string[] rolesNames)
Parameters
Type | Name | Description |
---|---|---|
string[] | rolesNames | one or more roles that has access |
RoutePrefixOverride(string)
specify an override route prefix for this endpoint if a global route prefix is enabled.
this is ignored if a global route prefix is not configured.
global prefix can be ignored by setting string.Empty
Declaration
protected void RoutePrefixOverride(string routePrefix)
Parameters
Type | Name | Description |
---|---|---|
string | routePrefix | route prefix value |
Route<T>(string, bool)
get the value of a given route parameter by specifying the resulting type and param name. NOTE: an automatic validation error is sent to the client when value retrieval is not successful.
Declaration
protected T? Route<T>(string paramName, bool isRequired = true)
Parameters
Type | Name | Description |
---|---|---|
string | paramName | route parameter name |
bool | isRequired | set to false for disabling the automatic validation error |
Returns
Type | Description |
---|---|
T | the value if retrieval is successful or null if |
Type Parameters
Name | Description |
---|---|
T | type of the result |
Routes(params string[])
specify one or more route patterns this endpoint should be listening for
Declaration
protected void Routes(params string[] patterns)
Parameters
Type | Name | Description |
---|---|---|
string[] | patterns |
SendAsync(TResponse, int, CancellationToken)
send the supplied response dto serialized as json to the client.
Declaration
protected Task SendAsync(TResponse response, int statusCode = 200, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
TResponse | response | the object to serialize to json |
int | statusCode | optional custom http status code |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendBytesAsync(byte[], string?, string, DateTimeOffset?, bool, CancellationToken)
send a byte array to the client
Declaration
protected Task SendBytesAsync(byte[] bytes, string? fileName = null, string contentType = "application/octet-stream", DateTimeOffset? lastModified = null, bool enableRangeProcessing = false, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
byte[] | bytes | the bytes to send |
string | fileName | |
string | contentType | optional content type to set on the http response |
DateTimeOffset? | lastModified | optional last modified date-time-offset for the data stream |
bool | enableRangeProcessing | optional switch for enabling range processing |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendCreatedAtAsync(string, object?, TResponse, bool, CancellationToken)
send a 201 created response with a location header containing where the resource can be retrieved from.
WARNING: this method is only supported on single verb/route endpoints. it will not produce a `Location` header if used in a multi verb or multi route endpoint.
Declaration
protected Task SendCreatedAtAsync(string endpointName, object? routeValues, TResponse responseBody, bool generateAbsoluteUrl = false, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
string | endpointName | the name of the endpoint to use for link generation (openapi route id) |
object | routeValues | a route values object with key/value pairs of route information |
TResponse | responseBody | the content to be serialized in the response body |
bool | generateAbsoluteUrl | set to true for generating a absolute url instead of relative url for the location header |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendCreatedAtAsync<TEndpoint>(object?, TResponse, Http?, int?, bool, CancellationToken)
send a 201 created response with a location header containing where the resource can be retrieved from.
HINT: if pointing to an endpoint with multiple verbs, make sure to specify the 'verb' argument and if pointing to a multi route endpoint, specify the 'routeNumber' argument.
WARNING: this overload will not add a location header if you've set a custom endpoint name using .WithName() method. use the other overload that accepts a string endpoint name instead.
Declaration
protected Task SendCreatedAtAsync<TEndpoint>(object? routeValues, TResponse responseBody, Http? verb = null, int? routeNumber = null, bool generateAbsoluteUrl = false, CancellationToken cancellation = default) where TEndpoint : IEndpoint
Parameters
Type | Name | Description |
---|---|---|
object | routeValues | a route values object with key/value pairs of route information |
TResponse | responseBody | the content to be serialized in the response body |
Http? | verb | only useful when pointing to a multi verb endpoint |
int? | routeNumber | only useful when pointing to a multi route endpoint |
bool | generateAbsoluteUrl | set to true for generating a absolute url instead of relative url for the location header |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
Type Parameters
Name | Description |
---|---|
TEndpoint | the type of the endpoint where the resource can be retrieved from |
SendEmptyJsonObject(CancellationToken)
send an empty json object in the body
Declaration
protected Task SendEmptyJsonObject(CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendErrorsAsync(int, CancellationToken)
send a 400 bad request with error details of the current validation failures
Declaration
protected Task SendErrorsAsync(int statusCode = 400, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
int | statusCode | the status code for the error response |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendEventStreamAsync<T>(string, IAsyncEnumerable<T>, CancellationToken)
start a "server-sent-events" data stream for the client asynchronously without blocking any threads
Declaration
protected Task SendEventStreamAsync<T>(string eventName, IAsyncEnumerable<T> eventStream, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
string | eventName | the name of the event stream |
IAsyncEnumerable<T> | eventStream | an IAsyncEnumerable that is the source of the data |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
Type Parameters
Name | Description |
---|---|
T | the type of the objects being sent in the event stream |
SendFileAsync(FileInfo, string, DateTimeOffset?, bool, CancellationToken)
send a file to the client
Declaration
protected Task SendFileAsync(FileInfo fileInfo, string contentType = "application/octet-stream", DateTimeOffset? lastModified = null, bool enableRangeProcessing = false, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
FileInfo | fileInfo | |
string | contentType | optional content type to set on the http response |
DateTimeOffset? | lastModified | optional last modified date-time-offset for the data stream |
bool | enableRangeProcessing | optional switch for enabling range processing |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendForbiddenAsync(CancellationToken)
send a 403 unauthorized response
Declaration
protected Task SendForbiddenAsync(CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendHeadersAsync(Action<IHeaderDictionary>, int, CancellationToken)
send headers in response to a HEAD request
Declaration
protected Task SendHeadersAsync(Action<IHeaderDictionary> headers, int statusCode = 200, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
Action<IHeaderDictionary> | headers | an action to be performed on the headers dictionary of the response |
int | statusCode | optional custom http status code |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendInterceptedAsync(object, int, CancellationToken)
sends an object serialized as json to the client. if a response interceptor has been defined, then that will be executed before the normal response is sent.
Declaration
protected Task SendInterceptedAsync(object response, int statusCode = 200, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
object | response | the object to serialize to json |
int | statusCode | optional custom http status code |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
Exceptions
Type | Condition |
---|---|
InvalidOperationException | will throw if an interceptor has not been defined against the endpoint or globally |
SendNoContentAsync(CancellationToken)
send a 204 no content response
Declaration
protected Task SendNoContentAsync(CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendNotFoundAsync(CancellationToken)
send a 404 not found response
Declaration
protected Task SendNotFoundAsync(CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendOkAsync(CancellationToken)
send an http 200 ok response without any body
Declaration
protected Task SendOkAsync(CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendOkAsync(TResponse, CancellationToken)
send an http 200 ok response with the supplied response dto serialized as json to the client.
Declaration
protected Task SendOkAsync(TResponse response, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
TResponse | response | the object to serialize to json |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendRedirectAsync(string, bool, CancellationToken)
send a 302/301 redirect response
Declaration
protected Task SendRedirectAsync(string location, bool isPermanant = false, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
string | location | the location to redirect to |
bool | isPermanant | set to true for a 301 redirect. 302 is the default. |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendResultAsync(IResult)
Declaration
protected Task SendResultAsync(IResult result)
Parameters
Type | Name | Description |
---|---|---|
IResult | result | the IResult instance to execute such as:
|
Returns
Type | Description |
---|---|
Task |
SendStreamAsync(Stream, string?, long?, string, DateTimeOffset?, bool, CancellationToken)
send the contents of a stream to the client
Declaration
protected Task SendStreamAsync(Stream stream, string? fileName = null, long? fileLengthBytes = null, string contentType = "application/octet-stream", DateTimeOffset? lastModified = null, bool enableRangeProcessing = false, CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
Stream | stream | the stream to read the data from |
string | fileName | and optional file name to set in the content-disposition header |
long? | fileLengthBytes | optional total size of the file/stream |
string | contentType | optional content type to set on the http response |
DateTimeOffset? | lastModified | optional last modified date-time-offset for the data stream |
bool | enableRangeProcessing | optional switch for enabling range processing |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendStringAsync(string, int, string, CancellationToken)
send the supplied string content to the client.
Declaration
protected Task SendStringAsync(string content, int statusCode = 200, string contentType = "text/plain", CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
string | content | the string to write to the response body |
int | statusCode | optional custom http status code |
string | contentType | optional content type header value |
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SendUnauthorizedAsync(CancellationToken)
send a 401 unauthorized response
Declaration
protected Task SendUnauthorizedAsync(CancellationToken cancellation = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellation | optional cancellation token. if not specified, the |
Returns
Type | Description |
---|---|
Task |
SerializerContext<TContext>()
specify the type of the json serializer context if code generation for request/response dtos is being used. the json serializer context will be instantiated with SerializerOptions from the UseFastEndpoints(...) call.
Declaration
protected void SerializerContext<TContext>() where TContext : JsonSerializerContext
Type Parameters
Name | Description |
---|---|
TContext | the type of the json serializer context for this endpoint |
SerializerContext<TContext>(TContext)
specify the json serializer context if code generation for request/response dtos is being used by supplying your own instance.
Declaration
protected void SerializerContext<TContext>(TContext serializerContext) where TContext : JsonSerializerContext
Parameters
Type | Name | Description |
---|---|---|
TContext | serializerContext |
Type Parameters
Name | Description |
---|---|
TContext | the type of the json serializer context for this endpoint |
Summary(EndpointSummary)
provide a summary/description for this endpoint to be used in swagger/ openapi
Declaration
protected void Summary(EndpointSummary endpointSummary)
Parameters
Type | Name | Description |
---|---|---|
EndpointSummary | endpointSummary | an endpoint summary instance |
Summary(Action<EndpointSummary<TRequest>>)
provide a summary/description for this endpoint to be used in swagger/ openapi
Declaration
protected void Summary(Action<EndpointSummary<TRequest>> endpointSummary)
Parameters
Type | Name | Description |
---|---|---|
Action<EndpointSummary<TRequest>> | endpointSummary | an action that sets values of an endpoint summary object |
Summary(Action<EndpointSummary>)
provide a summary/description for this endpoint to be used in swagger/ openapi
Declaration
protected void Summary(Action<EndpointSummary> endpointSummary)
Parameters
Type | Name | Description |
---|---|---|
Action<EndpointSummary> | endpointSummary | an action that sets values of an endpoint summary object |
Tags(params string[])
specify one or more string tags for this endpoint so they can be used in the exclusion filter during registration.
HINT: these tags have nothing to do with swagger tags!
Declaration
protected void Tags(params string[] endpointTags)
Parameters
Type | Name | Description |
---|---|---|
string[] | endpointTags | the tag values to associate with this endpoint |
Throttle(int, double, string?)
rate limit requests to this endpoint based on a request http header sent by the client.
Declaration
protected void Throttle(int hitLimit, double durationSeconds, string? headerName = null)
Parameters
Type | Name | Description |
---|---|---|
int | hitLimit | how many requests are allowed within the given duration |
double | durationSeconds | the frequency in seconds where the accrued hit count should be reset |
string | headerName | the name of the request header used to uniquely identify clients.
header name can also be configured globally using |
ThrowError(ValidationFailure, int?)
adds a FluentValidation.Results.ValidationFailure to the validation failure collection of the endpoint and send back a 400 bad request with error details immediately interrupting handler execution flow. if there are any vallidation failures, no execution will continue past this call.
Declaration
public void ThrowError(ValidationFailure failure, int? statusCode = null)
Parameters
Type | Name | Description |
---|---|---|
ValidationFailure | failure | the validation failure to add |
int? | statusCode | an optional status code to be used when building the error response |
ThrowError(Expression<Func<TRequest, object?>>, string, int?)
adds an error message for the specified property of the request dto and sends back a 400 bad request with error details immediately interrupting handler execution flow. no execution will continue past this call.
Declaration
public void ThrowError(Expression<Func<TRequest, object?>> property, string errorMessage, int? statusCode = null)
Parameters
Type | Name | Description |
---|---|---|
Expression<Func<TRequest, object>> | property | the property to add the error message for |
string | errorMessage | the error message |
int? | statusCode | an optional status code to be used when building the error response |
ThrowError(string, int?)
add a "GeneralError" to the validation failure list and send back a 400 bad request with error details immediately interrupting handler execution flow. if there are any vallidation failures, no execution will continue past this call.
Declaration
public void ThrowError(string message, int? statusCode = null)
Parameters
Type | Name | Description |
---|---|---|
string | message | the error message |
int? | statusCode | an optional status code to be used when building the error response |
ThrowIfAnyErrors(int?)
interrupt the flow of handler execution and send a 400 bad request with error details if there are any validation failures in the current request. if there are no validation failures, execution will continue past this call.
Declaration
public void ThrowIfAnyErrors(int? statusCode = null)
Parameters
Type | Name | Description |
---|---|---|
int? | statusCode | an optional status code to be used when building the error response |
TryResolve(Type)
try to resolve an instance for the given type from the dependency injection container. will return null if unresolvable.
Declaration
public object? TryResolve(Type typeOfService)
Parameters
Type | Name | Description |
---|---|---|
Type | typeOfService | the type of the service to resolve |
Returns
Type | Description |
---|---|
object |
TryResolve<TService>()
try to resolve an instance for the given type from the dependency injection container. will return null if unresolvable.
Declaration
public TService? TryResolve<TService>() where TService : class
Returns
Type | Description |
---|---|
TService |
Type Parameters
Name | Description |
---|---|
TService | the type of the service to resolve |
Validator<TValidator>()
specify the validator that should be used for this endpoint.
TIP: you only need to call this method if you have more than one validator for the same request dto in the solution or if you just want to be explicit about what validator is used by the endpoint.
Declaration
protected void Validator<TValidator>() where TValidator : IValidator
Type Parameters
Name | Description |
---|---|
TValidator | the type of the validator |
Verbs(params Http[])
specify one or more http method verbs this endpoint should be accepting requests for
Declaration
protected void Verbs(params Http[] methods)
Parameters
Type | Name | Description |
---|---|---|
Http[] | methods |
Verbs(params string[])
specify one or more http method verbs this endpoint should be accepting requests for
Declaration
public override sealed void Verbs(params string[] methods)
Parameters
Type | Name | Description |
---|---|---|
string[] | methods |
Overrides
Version(int, int?)
specify the version of the endpoint if versioning is enabled
Declaration
protected void Version(int version, int? deprecateAt = null)
Parameters
Type | Name | Description |
---|---|---|
int | version | the version of this endpoint |
int? | deprecateAt | the version group number starting at which this endpoint should not be included in swagger document |