如果你需要一個客戶端應用程序來檢查Web API服務器,看看服務器的文件的版本比客戶端版本更新,您可以設置服務器,通過執行以下步驟來完成:
添加適當的方法來存儲庫接口,如:
HttpResponseMessage GetCervezaBeberUpdate(string clientVersion);
此添加到相應的控制器類(其中,控制器名稱是「HenryFieldingController」):
[Route("api/HenryFielding/GetUpdatedCervezaBeber")]
public HttpResponseMessage GetUpdate(string clientVersion)
{
return _tomJonesRepository.GetCervezaBeberUpdate(clientVersion);
}
添加適當的方法來具體的庫類,如:
public HttpResponseMessage GetCervezaBeberUpdate(string clientVersion)
{
var binaryFilePath = HostingEnvironment.MapPath(@"~\App_Data\CervezaBeber.exe");
FileVersionInfo currentVersion = FileVersionInfo.GetVersionInfo(binaryFilePath);
if (!ServerFileIsNewer(clientVersion, currentVersion))
{
result = new HttpResponseMessage(HttpStatusCode.NoContent);
}
else
{
var stream = new FileStream(binaryFilePath, FileMode.Open);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
}
return result;
}
還要添加方法在庫類GetCervezaBeberUpdate()調用:
private bool ServerFileIsNewer(string clientFileVersion, FileVersionInfo serverFile)
{
Version client = new Version(clientFileVersion);
Version server = new Version(string.Format("{0}.{1}.{2}.{3}", serverFile.FileMajorPart, serverFile.FileMinorPart, serverFile.FileBuildPart, serverFile.FilePrivatePart));
return server > client;
}
現在,客戶可以通過撥打該傳遞一個URI這樣對服務器:
http://<servername>:<portnumber>/api/
<controllername>?clientVersion=<clientversionquad>
或者,更字面例如,在事件服務器的名稱爲「鴨嘴獸」,使用的端口是424 2,該控制器被命名爲HenryFieldingController,並且客戶端目前有文件的版本是3.1.4.1:
http://Platypus:4242/api/HenryFielding?clientVersion=3.1.4.1
爲自由的,在啤酒(你/我的心願!)溢價,這裏的一些代碼客戶端可以使用服務器的響應保存到文件(通過這一個URI如上面所示):
private void DownloadTheFile(string uri)
{
var outputFileName = "Platypus.exe";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
// From here on (including the CopyStream() method) derived from Jon Skeet's
// answer at http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}", outputFileName));
}
}
}
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
這可能幫助:http://www.codeproject.com/Tips/730360/How- to-Conditionally-Return-a-Binary-File-from-a –