C# HttpPost和webapi

C# HttpPost和webapi,c#,post,asp.net-mvc-4,C#,Post,Asp.net Mvc 4,我创建了一个API,它接受一个文件作为输入并处理它。 样品是这样的 [HttpPost] public string ProfileImagePost(HttpPostedFile HttpFile) { //rest of the code } 然后我推荐了一个客户,让他按如下方式使用这个 string path = @"abc.csv"; FileStream rdr = new FileStream(path, FileMode.

我创建了一个API,它接受一个文件作为输入并处理它。 样品是这样的

[HttpPost]
    public string ProfileImagePost(HttpPostedFile HttpFile)
    {

      //rest of the code
     }
然后我推荐了一个客户,让他按如下方式使用这个

 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();
但我在客户端得到了500个错误。 帮帮我,伙计们


Thanx提前…

ASP.NET Web API不适用于
HttpPostedFile
。相反,您应该使用
MultipartFormDataStreamProvider
,如中所示

而且你的客户端呼叫是错误的。您已将
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());
    }
}

代替HttpPostedFile,直接从客户端以流的形式发送文件,并在服务器端以流的形式读取文件,如:

 //read uploaded csv file at server side
 Stream csvStream = HttpContext.Current.Request.Files[0].InputStream;

//Send file from client 
 public static void PostFile()
 {
       string[] files = { @"C:\Test.csv" };

        string url = "http://localhost/abc/../test.xml";
        long length = 0;
        string boundary = "----------------------------" +
        DateTime.Now.Ticks.ToString("x");

        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
        boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.KeepAlive = true;
        httpWebRequest2.Credentials =
        System.Net.CredentialCache.DefaultCredentials;

        Stream memStream = new System.IO.MemoryStream();
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
        boundary + "\r\n");

        string formdataTemplate = "\r\n--" + boundary +
        "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

        memStream.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

        for (int i = 0; i < files.Length; i++)
        {
            //string header = string.Format(headerTemplate, "file" + i, files[i]);
            string header = string.Format(headerTemplate, "uplTheFile", files[i]);

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

            memStream.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(files[i], FileMode.Open,
            FileAccess.Read);
            byte[] buffer = new byte[1024];

            int bytesRead = 0;

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            memStream.Write(boundarybytes, 0, boundarybytes.Length);
            fileStream.Close();
        }

        httpWebRequest2.ContentLength = memStream.Length;
        Stream requestStream = httpWebRequest2.GetRequestStream();

        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        requestStream.Close();

        WebResponse webResponse2 = httpWebRequest2.GetResponse();

        Stream stream2 = webResponse2.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);

        webResponse2.Close();
        httpWebRequest2 = null;
        webResponse2 = null;
    }
//读取服务器端上传的csv文件
Stream csvStream=HttpContext.Current.Request.Files[0]。InputStream;
//从客户端发送文件
公共静态void PostFile()
{
字符串[]文件={@“C:\Test.csv”};
字符串url=”http://localhost/abc/../test.xml";
长长度=0;
字符串边界=“------------------------------------”+
DateTime.Now.Ticks.ToString(“x”);
HttpWebRequest httpWebRequest2=(HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType=“多部分/表单数据;边界=”+
边界;
httpWebRequest2.Method=“POST”;
httpWebRequest2.KeepAlive=true;
httpWebRequest2.凭据=
System.Net.CredentialCache.DefaultCredentials;
Stream memStream=new System.IO.MemoryStream();
byte[]boundarybytes=System.Text.Encoding.ASCII.GetBytes(“\r\n--”+
边界+“\r\n”);
字符串formdataTemplate=“\r\n--”+边界+
“\r\n内容处理:表单数据;名称=\”{0}\”;\r\n\r\n{1}”;
memStream.Write(boundarybytes,0,boundarybytes.Length);
string headerTemplate=“内容处置:表单数据;名称=\”{0}\“文件名=\”{1}\“\r\n内容类型:应用程序/八位字节流\r\n\r\n”;
for(int i=0;i
您应该遵守webapi路由命名约定,以避免一些麻烦

所有名为PostSomething()的方法都将被接受为HttpPost。它们的参数签名将告诉它们,您需要两个同名的

因此,调用您的WebApi方法postrofileimage(HttpPostedFile文件),然后您可以发布到http:///api// 将文件作为数据


WebApi中的路由基本错误是HTTP/500的根本原因,并且会导致异常情况。

以下是我发布屏幕截图的代码 客户端

    public void PostMethod()
    {
    ImageConverter converter = new ImageConverter();
    var bytes = (byte[])converter.ConvertTo(bmpScreenshot, typeof(byte[]));
    StringConverter s = new StringConverter();

    string uri = "http://localhost:3844/api/upload";

    byte[] postBytes = bytes;
    string str = Properties.Settings.Default.token.ToString(); //after login user receives a response token, it is stored in the application settings. All Posts save in db with a this token

    byte[] bA = ASCIIEncoding.ASCII.GetBytes(str);

    MultipartFormDataContent multiPartData = new MultipartFormDataContent();

    ByteArrayContent byteArrayContent = new ByteArrayContent(postBytes);
    ByteArrayContent bAC = new ByteArrayContent(bA);
    multiPartData.Add(bAC, "token");
    multiPartData.Add(byteArrayContent,"picture");

    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, uri);
    requestMessage.Content = multiPartData;

    HttpClient httpClient = new HttpClient();
    Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage);
    HttpResponseMessage httpResponse = httpRequest.Result;
    HttpContent responseContent = httpResponse.Content;
}
public void PostMethod()
{
ImageConverter converter=新的ImageConverter();
var bytes=(byte[])ConvertTo(bmpScreenshot,typeof(byte[]);
StringConverter s=新的StringConverter();
字符串uri=”http://localhost:3844/api/upload";
字节[]后字节=字节;
string str=Properties.Settings.Default.token.ToString();//登录用户收到响应令牌后,它将存储在应用程序设置中。所有帖子都使用此令牌保存在数据库中
字节[]bA=ASCIIEncoding.ASCII.GetBytes(str);
MultipartFormDataContent multiPartData=新的MultipartFormDataContent();
ByteArrayContent ByteArrayContent=新的ByteArrayContent(postBytes);
ByteArray内容bAC=新的ByteArray内容(bA);
multiPartData.Add(bAC,“令牌”);
multiPartData.Add(byteArrayContent,“picture”);
HttpRequestMessage requestMessage=新的HttpRequestMessage(HttpMethod.Post,uri);
requestMessage.Content=multiPartData;
HttpClient HttpClient=新HttpClient();
任务httpRequest=httpClient.SendAsync(requestMessage);
HttpResponseMessage httpResponse=httpRequest.Result;
HttpContent responseContent=httpResponse.Content;
}
服务器端

public class UploadController : ApiController
    {
public masterEntities context = new masterEntities();
public ImgEntitySet imgEntity = new ImgEntitySet();
public async Task<HttpResponseMessage> PostRawBufferManual()
{
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider("~/App_Data");
MultipartFileStreamProvider dataContent = await Request.Content.ReadAsMultipartAsync(streamProvider);
            foreach (HttpContent data in dataContent.Contents)
            {
                string fileName = data.Headers.ContentDisposition.Name;
                byte[] n = await data.ReadAsByteArrayAsync();
                string m = Encoding.ASCII.GetString(n);
                int z = int.Parse(m);
                imgEntity.UID = z;
                break;
            }
            foreach (HttpContent data in dataContent.Contents)
            {
                string fileNamePicture = data.Headers.ContentDisposition.Name;
                if (fileNamePicture == "picture")
                {
                    byte[] b = await data.ReadAsByteArrayAsync();
                    imgEntity.Image = b;
                }
            }

            context.ImgEntitySet.Add(imgEntity);
            context.SaveChanges();
            return Request.CreateResponse(HttpStatusCode.OK );
        }
}
公共类上载控制器:ApiController
{
公共主实体上下文=新主实体();
公共ImgEntitySet imgEntity=新ImgEntitySet();
公共异步任务PostRawBufferManual()
{
MultipartFormDataStreamProvider streamProvider=新的MultipartFormDataStreamProvider(“~/App_Data”);
MultipartFileStreamProvider dataContent=wait Request.Content.ReadAsMultipartAsync(streamProvider);
foreach(dataContent.Contents中的HttpContent数据)
{
字符串文件名=data.Headers.ContentDisposition.Name;
字节[]n=等待数据。ReadAsByteArrayAsync();
字符串m
public class UploadController : ApiController
    {
public masterEntities context = new masterEntities();
public ImgEntitySet imgEntity = new ImgEntitySet();
public async Task<HttpResponseMessage> PostRawBufferManual()
{
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider("~/App_Data");
MultipartFileStreamProvider dataContent = await Request.Content.ReadAsMultipartAsync(streamProvider);
            foreach (HttpContent data in dataContent.Contents)
            {
                string fileName = data.Headers.ContentDisposition.Name;
                byte[] n = await data.ReadAsByteArrayAsync();
                string m = Encoding.ASCII.GetString(n);
                int z = int.Parse(m);
                imgEntity.UID = z;
                break;
            }
            foreach (HttpContent data in dataContent.Contents)
            {
                string fileNamePicture = data.Headers.ContentDisposition.Name;
                if (fileNamePicture == "picture")
                {
                    byte[] b = await data.ReadAsByteArrayAsync();
                    imgEntity.Image = b;
                }
            }

            context.ImgEntitySet.Add(imgEntity);
            context.SaveChanges();
            return Request.CreateResponse(HttpStatusCode.OK );
        }
}