所以我在CMSController(MVC Web应用程序)中有这个方法:
[HttpPost]
public bool UploadFile(Stream file)
{
return file != null;
}
与该项目一起,我创建了另一个用于测试的控制台应用程序,并且该应用程序有一个功能,如下所示:
static void Main(string[] args)
{
//Console.ReadLine();
var stream = new FileStream(@"C:\Users\MyUsername\Desktop\test.txt", FileMode.Open);
var file = new StreamContent(stream);
var formData = new MultipartFormDataContent();
formData.Add(file, "file", "file");
//"http://localhost:49200/api/users/currentUsers"
string actionURL = "http://localhost:49200/api/cms/uploadFIle";
var request = new HttpRequestMessage(HttpMethod.Post, actionURL);
request.Headers.Add("Accept", "application/xml");
request.Headers.Add("enctype", "application/octet-stream");
request.Content = formData;
using (var client = new HttpClient())
using (var response = client.SendAsync(request))
{
response.Wait();
var resContent = response.Result.Content.ReadAsStringAsync();
resContent.Wait();
Console.WriteLine(resContent.Result);
//Console.WriteLine(response.Result.RequestMessage.Content.ReadAsStringAsync());
}
Console.ReadLine();
}
我总是收到错误:
<Error>
<Message>The request entity's media type 'multipart/form-data' is not supported for this resource.</Message>
<ExceptionMessage>No MediaTypeFormatter is available to read an object of type 'Stream' from content with media type 'multipart/form-data'.</ExceptionMessage>
<ExceptionType>System.Net.Http.UnsupportedMediaTypeException</ExceptionType>
<StackTrace> at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)</StackTrace>
</Error>
我尝试使用request.Headers.Add("enctype", "image/jpeg");
上传图片,我尝试过(在CMSController.UploadFile中)public bool UploadFile(HttpPostedFileBase file)
,我尝试this code,我尝试通过添加来编辑网络配置
<webHttpBinding>
<binding name="CMSController.UploadFIle" maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
transferMode="Streamed"
sendTimeout="00:05:00">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"></transport>
</security>
</binding>
</webHttpBinding>
但我总是得到同样的错误(如上所述)。
如何使用Controller的功能和控制台应用程序上传文件? (如果我没有提供足够的信息,请在下面评论,我会解释/编辑问题/等)