【发布时间】:2021-04-05 12:25:00
【问题描述】:
创建了一个 POST API,它基本上将文件保存在一个目录中。
当来自客户端的多个请求时,异步代码是否会使我的 API 更好地处理可伸缩性?
目前,代码同步工作。
我应该让每个方法都异步吗?我应该把关键字 await 放在哪里?
任务:
任务 1:读取请求内容 (XML)
任务 2:如果尚未创建目录,请创建目录
任务 3:使文件名独一无二
将文件保存到目录
[System.Web.Mvc.HttpPost]
public IHttpActionResult Post(HttpRequestMessage request)
{
try
{
string contentResult = string.Empty;
ValidateRequest(ref contentResult, request);
//contentResult = "nothing";
//Validation of the post-requested XML
//XmlReaderSettings(contentResult);
using (StringReader s = new StringReader(contentResult))
{
doc.Load(s);
}
string path = MessagePath;
//Directory creation
DirectoryInfo dir = Directory.CreateDirectory($@"{path}\PostRequests");
string dirName = dir.Name;
//Format file name
var uniqueFileName = UniqueFileNameFormat();
doc.Save($@"{path}\{dirName}\{uniqueFileName}");
}
catch (Exception e)
{
LogService.LogToEventLog($"Error occured while receiving a message from messagedistributor: " + e.ToString(), System.Diagnostics.EventLogEntryType.Error);
throw e;
}
LogService.LogToEventLog($"Message is received sucessfully from messagedistributor: ", System.Diagnostics.EventLogEntryType.Information);
return new ResponseMessageResult(Request.CreateResponse((HttpStatusCode)200));
}
【问题讨论】:
标签: c# api post async-await task