Skip to content

Instantly share code, notes, and snippets.

@alexsandro-xpt
Last active March 9, 2020 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexsandro-xpt/f014ac03b572e422e8138b4f5215f9ec to your computer and use it in GitHub Desktop.
Save alexsandro-xpt/f014ac03b572e422e8138b4f5215f9ec to your computer and use it in GitHub Desktop.
using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Json;
namespace WebApplicationTestUrl
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
//app.UseRouting();
//app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapPost("/api/device", async context =>
{
var cancellationToken = context.RequestAborted;
var model = await ReadModelAsync(context.Request.BodyReader, cancellationToken);
await context.Response.WriteAsync("Hello World!");
});
});
}
private static async Task<DeviceModel> ReadModelAsync(PipeReader reader, CancellationToken cancellationToken)
{
DeviceModel model = null;
while (!cancellationToken.IsCancellationRequested)
{
var readResult = await reader.ReadAsync(cancellationToken);
var buffer = readResult.Buffer;
var position = buffer.PositionOf((byte)'}');
if (position != null)
{
if (buffer.IsSingleSegment)
{
model = JsonSerializer.Deserialize<DeviceModel>(buffer.FirstSpan, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
else
{
using var document = JsonDocument.Parse(buffer);
if (document.RootElement.TryGetProperty("StationId", out var pathProperty)
&& pathProperty.GetType() == typeof(string))
{
model = new DeviceModel
{
StationId = new Guid(pathProperty.GetString())
};
}
}
}
reader.AdvanceTo(buffer.Start, buffer.End);
if (readResult.IsCompleted) break;
}
return model;
}
}
public class DeviceModel
{
public Guid StationId { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment