【发布时间】:2016-12-20 11:26:02
【问题描述】:
我必须在本地机器上开发类似于 ASP.NET C# 控制台应用程序或 Web 服务的东西,它能够从网站获取数据并发送回一些数据。 我的网站在离我很远的服务器上。我还有一台连接到打印机的本地机器。 任务如下:有人将一些数据放在网站上的文本框中,选择正确的打印机并按打印(因此网站需要连接到本地机器的可用打印机的当前列表)。本地机器获取并打印出数据,然后发回一些确认信息。
我正在使用 Web Api 在网站和控制台应用程序之间进行通信。
这就是 Web API 现在的样子:
public class LabelController : UmbracoApiController
{
Label[] labels = new Label[]
{
new Label { Product="Black Top", Location="T1", VariantSKU="1111" }
};
[HttpGet]
[ActionName("SendLabel")]
public Label SendLabel(Label currentLabel)
{
Label lbl = currentLabel;
return lbl;
}
[HttpGet]
[ActionName("SendAllLabels")]
public IEnumerable<Label> SendAllLabels()
{
return labels;
}
[HttpPost]
[ActionName("GetPrinters")]
public void GetPrinters([FromBody]string value)
{
//Here I should get the list of printers from the local machine
}
}
这是我尝试从网站调用以将标签发送到本地机器的方式:
Label printlabel = new Label { Product = "Awesome T-Shirt", Location = "T1", VariantSKU = "0000000" };
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:49423/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var webapi = new LabelController();
webapi.SendLabel(printlabel);
}
这就是我在控制台应用程序中使用 Web API 的方式:
public class Label
{
public string Product { get; set; }
public string Location { get; set; }
public string VariantSKU { get; set; }
}
class Program
{
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:49423/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
PrintData();
PrinterList();
}
}
static void PrintData()
{
try
{
HttpResponseMessage resp = client.GetAsync("umbraco/api/Label/SendLabel").Result;
resp.EnsureSuccessStatusCode();
var label = resp.Content.ReadAsAsync<Label>().Result;
Console.WriteLine(label.Product);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static async void PrinterList()
{
var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
var name = printer.GetPropertyValue("Name");
var status = printer.GetPropertyValue("Status");
var isDefault = printer.GetPropertyValue("Default");
var isNetworkPrinter = printer.GetPropertyValue("Network");
// Here I should send the parameters back to the website
}
}
}
我的问题是我无法将标签放入 SendLabel 操作,并且我不知道如何将数据从控制台应用程序发送到网站。
谢谢!
【问题讨论】:
标签: c# asp.net asp.net-web-api asp.net-web-api2