use*_*770 3 c# post asp.net-mvc-4
我创建了一个API,它将文件作为输入并进行处理.样本是这样的......
[HttpPost]
public string ProfileImagePost(HttpPostedFile HttpFile)
{
//rest of the code
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个客户端来消费这个如下...
string path = @"abc.csv";
FileStream rdr = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] inData = new byte[rdr.Length];
rdr.Read(inData, 0, Convert.ToInt32(rdr.Length));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/abc/../ProfileImagePost");
req.KeepAlive = false;
req.ContentType = "multipart/form-data";
req.Method = "POST";
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
reqStream.Write(inData, 0, Convert.ToInt32(rdr.Length));
reqStream.Close();
HttpWebResponse TheResponse = (HttpWebResponse)req.GetResponse();
string TheResponseString1 = new StreamReader(TheResponse.GetResponseStream(), Encoding.ASCII).ReadToEnd();
TheResponse.Close();
Run Code Online (Sandbox Code Playgroud)
但是我在客户端遇到500错误.帮帮我吧.
提前完成了...
ASP.NET Web API无法使用HttpPostedFile
.相反,你应该使用MultipartFormDataStreamProvider
如图所示following tutorial
.
您的客户端电话也是错误的.您已设置为ContentType
,multipart/form-data
但您根本不尊重此编码.您只是将文件写入请求流.
让我们举一个例子:
public class UploadController : ApiController
{
public Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HostingEnvironment.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data
return Request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>
{
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以用a HttpClient
来调用这个API:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
class Program
{
static void Main(string[] args)
{
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri("http://localhost:16724/");
var fileContent = new ByteArrayContent(File.ReadAllBytes(@"c:\work\foo.txt"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Foo.txt"
};
content.Add(fileContent);
var result = client.PostAsync("/api/upload", content).Result;
Console.WriteLine(result.StatusCode);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6416 次 |
最近记录: |