Response Building¶
The response is represented as the IHttpResponse interface which defines HTTP status code, HTTP headers and HTTP body content. The basic implementation of the HttpResponse provides universal constructors to build any type of response. Also there are a few implementations to increase usability.
- TextHttpResponse represents a text response;
- JsonHttpResponse represents a JSON response;
- StreamHttpResponse represents a stream response of a given Content-Type;
- RedirectHttpResponse represents an HTTP redirect response;
- PrintViewHttpResponse represents a response of the Print View.
Besides several prepared responses were added which are used very often:
- HttpResponse.Ok represents the 200 OK response;
- HttpResponse.Unauthorized represents the 401 Unauthorized response;
- HttpResponse.Forbidden represents the 403 Forbidden response;
- HttpResponse.NotFound represents the 404 Not Found response.
Result Converters¶
The response can be any model and the final result will be determined by the ResultConverter which defines conversion rules from the source model to the IHttpResponse instance. If a module does not set the ResultConverter then the default conversion rules are used. They are represented in the DefaultHttpResultConverter class:
- IHttpResponse will be returned as is;
null
will be interpreted as HttpResponse.Ok;- int will be interpreted as a HTTP status code;
- string will be interpreted as TextHttpResponse;
- byte[], Stream and Func<Stream> will be interpreted as StreamHttpResponse;
- Exception will be interpreted as 500 Internal Server Error with the exception message;
- other objects will be interpreted as JsonHttpResponse.
Next converter wraps a result to the JSON object with a single property Result
.
builder.ResultConverter = result =>
{
return (result is IHttpResponse)
? (IHttpResponse)result
: new JsonHttpResponse(new { Result = result });
};
builder.Get["/some"] = request =>
{
return Task.FromResult<object>(123); // {"Result":123 }
};