我的Windows 10 UWP应用程序上有以下代码,用于将文件发送到WebAPI Web服务。
public async void Upload_FileAsync(string WebServiceURL, string FilePathToUpload)
{
//prepare HttpStreamContent
IStorageFile storageFile = await StorageFile.GetFileFromPathAsync(FilePathToUpload);
IRandomAccessStream stream=await storageFile.OpenAsync(FileAccessMode.Read);
Windows.Web.Http.HttpStreamContent streamContent = new Windows.Web.Http.HttpStreamContent(stream);
//send request
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
var client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.PostAsync(new Uri(WebServiceURL), streamContent);
string stringReadResult = await result.Content.ReadAsStringAsync();
}
以下是我尝试在Web服务中使用的控制器,但myFileBytes
始终具有空值。我尝试使用相同的结果添加[FromBody]
和[FromForm]
。
public class MyController : Controller
{
[HttpPost]
public async Task<bool> Upload_File(byte[] myFileBytes)
{
//...
}
}
我也尝试使用IFormFile
,结果相同。
public class MyController : Controller
{
[HttpPost]
public async Task<bool> Upload_File(IFormFile myFileBytes)
{
//...
}
}
如何将文件传送到Web服务中的控制器?请帮忙!
答案 0 :(得分:1)
如同承诺的那样!我用过的东西:
在asp.net核心中,我有一个看起来像的控制器:
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpPost("Bytes")]
public void Bytes([FromBody]byte[] value)
{
}
[HttpPost("Form")]
public Task<IActionResult> Form([FromForm]List<IFormFile> files)
{
// see https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads
return Task.FromResult<IActionResult>(Ok());
}
}
UWP中的使用它来发送图像:
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(“ms-appx:///Assets/LockScreenLogo.png”));
try
{
var http = new HttpClient();
var formContent = new HttpMultipartFormDataContent();
var fileContent = new HttpStreamContent(await file.OpenReadAsync());
fileContent.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("image/png");
formContent.Add(fileContent, "files", "lockscreenlogo.png");
var response = await http.PostAsync(new Uri("http://localhost:15924/api/values/Form"), formContent);
response.EnsureSuccessStatusCode();
}
catch(Exception ex)
{
}
formContent.Add(fileContent, "files", "lockscreenlogo.png");
很重要。使用此特定覆盖