added reading from request

This commit is contained in:
Michael Nolan
2022-04-24 13:56:06 -05:00
parent ccdcf0b8f6
commit 7886cc120c
4 changed files with 82 additions and 5 deletions
+72 -1
View File
@@ -18,6 +18,77 @@ namespace Tesses.WebServer
public static class Extensions
{
/// <summary>
/// Read string from request body
/// </summary>
/// <param name="ctx">ServerContext</param>
/// <returns>the contents of request</returns>
public static async Task<string> ReadStringAsync(this ServerContext ctx)
{
string str = null;
using (var reader = new StreamReader(ctx.NetworkStream))
{
str = await reader.ReadToEndAsync();
}
return str;
}
/// <summary>
/// Read json from request body
/// </summary>
/// <param name="ctx">ServerContext</param>
/// <typeparam name="T">type of object (for scema)</typeparam>
/// <returns>object of type T with deserialized json data</returns>
public static async Task<T> ReadJsonAsync<T>(this ServerContext ctx)
{
var json=await ctx.ReadStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// Read request body to array
/// </summary>
/// <param name="ctx">ServerContext</param>
/// <returns>Request body data</returns>
public static async Task<byte[]> ReadBytesAsync(this ServerContext ctx)
{
MemoryStream strm = new MemoryStream();
await ctx.ReadToStreamAsync(strm);
return strm.ToArray();
}
/// <summary>
/// Read request body to stream
/// </summary>
/// <param name="ctx">ServerContext</param>
/// <param name="strm">Stream to write to</param>
public static async Task ReadToStreamAsync(this ServerContext ctx,Stream strm)
{
await ctx.NetworkStream.CopyToAsync(strm);
}
/// <summary>
/// Read request body to file
/// </summary>
/// <param name="ctx">ServerContext</param>
/// <param name="filename">name of file to write too, can be without extension</param>
/// <returns>file path with extension unless mimetype header is missing</returns>
public static async Task<string> ReadToFileAsync(this ServerContext ctx,string filename)
{
if(string.IsNullOrWhiteSpace(Path.GetExtension(filename)))
{
string val;
if(ctx.RequestHeaders.TryGetFirst("Content-Type",out val))
{
filename += $".{MimeTypesMap.GetExtension(val)}";
}
}
using(var f = File.Create(filename))
{
await ctx.NetworkStream.CopyToAsync(f);
}
return filename;
}
/// <summary>
/// Write headers to stream
/// </summary>
@@ -771,7 +842,7 @@ namespace Tesses.WebServer
IServer _server;
TcpListener _listener;
SslProtocols protocols;
public HttpServerListener(IPEndPoint endPoint,IServer server)
{
_listener = new TcpListener(endPoint);