[英]Sending file from MVC application to Web API performance
我的解決方案有兩個項目,一個是ASP.NET MVC(僅作為UI),另一個是ASP.NET Web API(作為Restful服務)。 我想將上傳的文件從MVC項目發送到Web API,並且在部署時,每個應用程序都將托管在不同的服務器上,因此我需要將所有文件集中在Web API服務器中。 我需要幫助在兩個選項(性能方面)之間進行比較:
[HttpPost]
public ActionResult UploadProfilePicture(HttpPostedFileBase file)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] Bytes = new byte[file.InputStream.Length + 1];
file.InputStream.Read(Bytes, 0, Bytes.Length);
var fileContent = new ByteArrayContent(Bytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var requestUri = "http://localhost:1963/api/upload";
var result = client.PostAsync(requestUri, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.Created)
{
List<string> m = result.Content.ReadAsAsync<List<string>>().Result;
ViewBag.Success = m.FirstOrDefault();
}
else
{
ViewBag.Failed = "Failed !" + result.Content.ToString();
}
}
}
return View();
}
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
System.IO.File.Copy("sourcePath in MVC server", "\\machinename\share folder path");
最佳表現是什么?
我懷疑具有直接文件訪問權限的選項2應該會提供更好的性能,因為所使用的協議針對傳輸二進制文件而進行了優化,而HTTP協議具有不同的用途。
但是,性能不應成為選擇解決方案的唯一標准。 如果在選項之間進行選擇,則還需要評估其他含義。
從體系結構和安全性的角度來看,選項2比選項1差,因為:
由於這些原因,只要性能足以滿足您的要求,我就選擇選項1。
或者,您也可以將文件從客戶端直接上傳到Web API,從而減少必須執行的上傳次數。
在選項1中,您將文件上傳兩次:從客戶端到托管MVC應用程序的服務器,然后從那里上傳到Web API。
在選項2中,似乎僅在上傳方面性能最佳,因為您是直接從客戶端調用Web Api。
但與往常一樣,這取決於您要實現的目標。
您應該使用瀏覽器(firefox或chrome)分析器來比較每個選項花費的時間。
每當您對性能有疑問時,都應該分析應用程序。 還請記住,性能是一項功能。
您可以使用此工具進行不同情況的分析[1]:
發現代碼中的熱點
發現代碼中的分配
兩者都做
隔離功能並迭代改進
[1] Ben Adams提出的工具
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.