BeetleX.FastHttpApi — это лёгкий и высокопроизводительный компонент HTTP-службы на платформе dotnet core, который поддерживает WebSocket и SSL.
[https://github.com/beetlex-io/BeetleX-Samples]
Раунд 20 (https://www.techempower.com/benchmarks/#section=data-r20&hw=ph&test=composite)
Install-Package BeetleX.FastHttpApi
[Controller]
class Program
{
private static BeetleX.FastHttpApi.HttpApiServer mApiServer;
static void Main(string[] args)
{
mApiServer = new BeetleX.FastHttpApi.HttpApiServer();
mApiServer.Options.LogLevel = BeetleX.EventArgs.LogType.Trace;
mApiServer.Options.LogToConsole = true;
mApiServer.Debug();//set view path with vs project folder
mApiServer.Register(typeof(Program).Assembly);
//mApiServer.Options.Port=80; set listen port to 80
mApiServer.Open();//default listen port 9090
Console.Write(mApiServer.BaseServer);
Console.Read();
}
// Get /hello?name=henry
// or
// Get /hello/henry
[Get(Route="{name}")]
public object Hello(string name)
{
return $"hello {name} {DateTime.Now}";
}
// Get /GetTime
public object GetTime()
{
return DateTime.Now;
}
}
mApiServer.Map("/", (ctx) =>
{
ctx.Result(new TextResult("map /"));
});
mApiServer.Map("/user/{id}", async (ctx) =>
{
ctx.Result(new TextResult((string)ctx.Data["id"]));
});
mApiServer.UrlRewrite.Add("/api/PostStream/{code}/{datacode}", "/api/PostStream");
mApiServer.UrlRewrite.Add("/api/PostStream/{code}", "/api/PostStream");
mApiServer.UrlRewrite.Add(null, "/gettime", "/time", null);
[RouteMap("/map/{code}")]
[RouteMap("/map/{code}/{customer}")]
public object Map(string code, string customer)
{
return new { code, customer };
}
Install-Package BeetleX.FastHttpApi.Hosting
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddSingleton<UserService>()
.UseBeetlexHttp(o => {
o.Port = 8080;
o.LogToConsole = true;
o.LogLevel = BeetleX.EventArgs.LogType.Debug;
o.SetDebug();
}, typeof(Program).Assembly);
});
builder.Build().Run();
BeetleX.FastHttpApi.EFCore.Extension
class Program
{
static void Main(string[] args)
{
HttpApiServer server = new HttpApiServer();
server.AddEFCoreDB<NorthwindEFCoreSqlite.NorthwindContext>();
server.Options.Port = 80;
server.Options.LogToConsole = true;
server.Options.LogLevel = EventArgs.LogType.Info;
server.Options.SetDebug();
server.Register(typeof(Program).Assembly);
server.AddExts("woff");
server.Open();
Console.Read();
}
}
[Controller]
public class Webapi
{
public DBObjectList<Customer> Customers(string name, string country, EFCoreDB<NorthwindContext> db)
{
Select<Customer> select = new Select<Customer>();
if (!string.IsNullOrEmpty(name))
select &= c => c.CompanyName.StartsWith(name);
if
*Обратите внимание, что в запросе присутствуют фрагменты кода, которые не удалось перевести. Это связано с тем, что некоторые конструкции специфичны для языка программирования C# и не имеют прямых аналогов в русском языке.* **Текст запроса:**
``` csharp
public class TextResult : ResultBase
{
public TextResult(string text)
{
Text = text == null ? "" : text;
}
public string Text { get; set; }
public override bool HasBody => true;
public override void Write(PipeStream stream, HttpResponse response)
{
stream.Write(Text);
}
}
Перевод на русский язык:
Класс TextResult наследуется от класса ResultBase:
public class TextResult: ResultBase
{
public TextResult (string text): base()
{
Text = text == null ? "" : text;
}
public string Text {get; set;}
public override bool HasBody => true;
public override void Write (PipeStream stream, HttpResponse response)
{
stream.Write (Text);
}
}
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )