我是ApiControllers的新手并测试从客户端向api发送文件并从此处保存。下面的代码确实有效,文件被复制"从客户端到服务器,但响应消息是" 204 No Content" - 我应该在这里注意什么吗?
ApiController代码是这样的:
[HttpPost]
[Route("api/UploadFile")]
public async Task UploadFile()
{
string fileName = "myfilename.txt";
Stream requestStream = await Request.Content.ReadAsStreamAsync();
using (FileStream fileStream = File.Create(@"C:\myDropFolder\" + fileName))
{
await requestStream.CopyToAsync(fileStream);
}
}
对客户端的调用如下所示,从控制台应用程序进行测试:
class Program
{
static void Main(string[] args)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:1741/api/UploadFile/");
request.Method = WebRequestMethods.Http.Post;
byte[] fileToSend = File.ReadAllBytes(@"C:\myDropFolder\tester.txt");
request.ContentLength = fileToSend.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
Console.ReadLine();
}
catch (Exception)
{
throw;
}
}
}
答案 0 :(得分:2)
Web API的POST默认响应状态代码为204,GET为200(Action Results in Web API 2)。除非您返回IHttpActionResult
然后显式返回200:
[HttpPost]
[Route("api/UploadFile")]
public async Task<IHttpActionResult> UploadFile()
{
string fileName = "myfilename.txt";
Stream requestStream = await Request.Content.ReadAsStreamAsync();
using (FileStream fileStream = File.Create(@"C:\myDropFolder\" + fileName))
{
await requestStream.CopyToAsync(fileStream);
}
return Ok();
}