无法使用Windows.Web.Http从UWP应用程序发送文件到WebAPI Web服务控制器
我在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 Upload_File(byte[] myFileBytes) { //... } }
我也尝试使用IFormFile
,结果相同。
public class MyController : Controller { [HttpPost] public async Task Upload_File(IFormFile myFileBytes) { //... } }
如何将文件传送到Web服务中的控制器? 请帮忙!
按照承诺! 我用过的:
- asp.net核心
- UWP
在asp.net核心我有一个看起来像这样的控制器:
[Route("api/[controller]")] public class ValuesController : Controller { [HttpPost("Bytes")] public void Bytes([FromBody]byte[] value) { } [HttpPost("Form")] public Task Form([FromForm]List files) { // see https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads return Task.FromResult(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");
很重要 使用此特定覆盖