我现在快疯了......我不明白为什么如果我在事件 button2_Click_2 中创建变量“服务器”,当它在 button3_Click_1 为空的情况下尝试访问它时。
我应该怎么做才能在 button3_Click_1 中访问它?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using TCCWindows.Lib;
using System.Web.Http.SelfHost;
using System.Web.Http;
namespace TCCWindows
{
public partial class FormPrincipal : Form
{
HttpSelfHostServer server;
HttpSelfHostConfiguration config;
public FormPrincipal()
{
InitializeComponent();
}
private void button2_Click_2(object sender, EventArgs e)
{
var config = new HttpSelfHostConfiguration(textBox1.Text);
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
HttpSelfHostServer server = new HttpSelfHostServer(config);
server.OpenAsync();
MessageBox.Show("Server is ready!");
}
private void button3_Click_1(object sender, EventArgs e)
{
server.CloseAsync();
}
}
public class ProductsController : ApiController
{
public string GetProductsByCategory(string category)
{
return (category ?? "Vazio");
}
}
}