我需要向现有库中添加一个非常简单的Web API,以便Python可以与应用程序通信.简单的请求/JSON响应.这比最初想象的更具挑战性.我习惯了NodeJ,在那里像Express这样的库只需几行代码就可以做到这一点.
显然,web服务器需要集成到图书馆中.我不能依赖IIS或任何web服务器.
这些教程遍布网络:
安装:Microsoft.AspNet.WebApi.OwinSelfHost
Main
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();
}
}
Startup
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);
}
}
Controller
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)
{
}
}
它看起来很简单,但在.NET6中不起作用.似乎存在兼容性问题.
我偶然发现了如下线索:
Self Hosting OWIN in .NET Core
NullReferenceException experienced with Owin on Startup .Net Core 2.0 - Settings?
然而,对于如何在现有的.NET6库中部署简单的Web API,我正在努力找到一个实用的答案.建议的解决方法不适合我.
如有任何建议,我们将不胜感激?我宁愿go 另一个图书馆吗?是ASP.NET不是正确的工具吗?