[英]Self-Hosted Web API in .NET 6
我需要向现有库添加一个非常简单的 Web API,以便 Python 可以与应用程序通信。 简单的请求/JSON 响应。 这比最初想象的更具挑战性。 我习惯了 NodeJS,像 Express 这样的库只需几行代码就可以做到这一点。
显然,Web 服务器需要集成到库中。 我不能依赖 IIS 或任何 Web 服务器。
这些类型的教程遍布网络:
安装:Microsoft.AspNet.WebApi.OwinSelfHost
主要的
static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/values").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
}
启动
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
控制器
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody] string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
看起来很简单,但是,它在 .NET 6 中不起作用。似乎存在兼容性问题。
我偶然发现了以下线程:
在启动 .Net Core 2.0 上使用 Owin 时遇到 NullReferenceException - 设置?
但是,我正在努力寻找关于如何在现有 .NET 6 库中部署简单 Web API 的实用答案。 建议的解决方法对我不起作用。
任何建议将被认真考虑 ? 我应该去不同的图书馆吗? ASP.NET 不是正确的工具吗?
ASP.NET Core 内置并默认启用 Web 服务器 - Kestrel ,因此无需设置 OWIN。 简单的设置可以这样看( WebApplication.CreateBuilder
在内部调用UseKestrel
):
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.