我的程序是为了自我托管Windows应用程序中的Web API。由于我在网络服务方面没有太多经验,因此我请求某人的帮助来解决问题。
我可以成功地制作控制台应用程序。但是,当我将其更改为Windows应用程序时,我的IDE会遇到错误"应用程序处于断路模式"。
控制台程序;
using System.Web.Http;
using System.Web.Http.SelfHost;
主要功能:
var config = new HttpSelfHostConfiguration("http://localhost:8080");
config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit."); // Removed in Win Form
Console.ReadLine(); // Removed in Win Form
}
API控制器类;我需要从"从body"属性中接收数据。
public class FieldsController : ApiController
{
[HttpPost]
public void PostAction([FromBody] Field model)
{
int patientID;
string name;
string age;
patientID = model.patientID;
name = model.patientName;
age = model.patientAge;
}
}
您可以更详细地说错误吗?我也以类似的方式完成了工作,我正在工作。在项目的解决方案中,我为WebAPI添加了一个新的类Libraray类型项目。从主要的Windows Form应用程序中,我正在探索WebAPI。WebAPI项目如下:
using System;
using System.ServiceModel;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace MYWebAPI
{
public class WebApiProgram : IDisposable
{
private string URL = "http://localhost:1234/";
private HttpSelfHostServer server;
public WebApiProgram()
{
}
public WebApiProgram(string url)
{
this.URL = url;
}
public void Dispose()
{
server.CloseAsync().Wait();
}
public void Start()
{
var config = new HttpSelfHostConfiguration(URL);
config.TransferMode = TransferMode.Streamed;
AddAPIRoute(config);
server = new HttpSelfHostServer(config);
var task = server.OpenAsync();
task.Wait();
//Console.WriteLine("Web API Server has started at:" + URL);
//Console.ReadLine();
}
private void AddAPIRoute(HttpSelfHostConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
从main(([program.cs file] winform applition我调用webapi start函数。
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main(string[] args)
{
//Start the webAPI
WebApiProgram.StartMain();
Thread.CurrentThread.CurrentCulture
= Thread.CurrentThread.CurrentUICulture
= CultureInfo.InvariantCulture;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var mainForm = new MainForm();
Application.Run(mainForm);
}
}