ITKeyword,专注技术干货聚合推荐

注册 | 登录

解决c# - Upload file using PUT verb in ASP.Net Web Api 2

itPublisher 分享于

2020腾讯云双十一活动,全年最低!!!(领取3500元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1073

【阿里云】双十一活动,全年抄底价,限时3天!(老用户也有),
入口地址https://www.aliyun.com/1111/home

推荐:File Upload using jQuery AJAX in ASP.NET Web API or Http handler (AJAX上传文件通过Web API或 http handler)

AJAX上传文件通过Web API或 http handler Upload file using jQuery AJAX in ASP.NET Web API This article provides an easy way to upload an image file usin

I would like to expose an ASP.Net Web Api 2 action using the HTTP PUT verb to upload files. This is coherent with our REST model as the API represents a remote file system (similar to WebDAV, but really simplified), so the client chooses the resource names (thus PUT is ideal and POST is not a logical choice).

The Web Api documentation describes how to upload files using multipart/form-data forms, but does not describe how to do it using PUT methods.

What would you use to test such an API (HTML multipart forms don't allow PUT verbs)? Would the server implementation look like the multipart implementation described in the web api documentation (using the MultipartStreamProvider), or should it look like this:

[HttpPut]
public async Task<HttpResponseMessage> PutFile(string resourcePath)
{
    Stream fileContent = await this.Request.Content.ReadAsStreamAsync();
    bool isNew = await this._storageManager.UploadFile(resourcePath, fileContent);
    if (isNew)
    {
        return this.Request.CreateResponse(HttpStatusCode.Created);
    }
    else
    {
        return this.Request.CreateResponse(HttpStatusCode.OK);
    }
}
c# http file-upload asp.net-web-api asp.net-web-api2
|
  this question
asked Jun 23 '15 at 13:15 Maxime Rossini 1,469 11 24

 | 

1 Answers
1

解决方法

After a few tests it seems the server-side code I posted as an example is correct. Here is an example, stripped out of any authentication/authorization/error handling code:

推荐:asp.net web api

官方的地址: http://www.asp.net/web-api 里面的资料很全,是学习的第一选择.建议多参考此资料 1.里面最简单直接的例子 http://www.asp.net/web-api/overview/get

[HttpPut]
[Route(@"api/storage/{*resourcePath?}")]
public async Task<HttpResponseMessage> PutFile(string resourcePath = "")
{
    // Extract data from request
    Stream fileContent = await this.Request.Content.ReadAsStreamAsync();
    MediaTypeHeaderValue contentTypeHeader = this.Request.Content.Headers.ContentType;
    string contentType =
        contentTypeHeader != null ? contentTypeHeader.MediaType : "application/octet-stream";

    // Save the file to the underlying storage
    bool isNew = await this._dal.SaveFile(resourcePath, contentType, fileContent);

    // Return appropriate HTTP status code
    if (isNew)
    {
        return this.Request.CreateResponse(HttpStatusCode.Created);
    }
    else
    {
        return this.Request.CreateResponse(HttpStatusCode.OK);
    }
}

A simple console app is enough to test it (using Web Api client libraries):

using (var fileContent = new FileStream(@"C:\temp\testfile.txt", FileMode.Open))
using (var client = new HttpClient())
{
    var content = new StreamContent(fileContent);
    content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
    client.BaseAddress = new Uri("http://localhost:81");
    HttpResponseMessage response =
        await client.PutAsync(@"/api/storage/testfile.txt", content);
}

|
  this answer
edited Dec 1 '15 at 9:37 answered Jun 24 '15 at 7:25 Maxime Rossini 1,469 11 24 1   It would be interesting to see how to write a proper unit test for this, rather than relying on running an HTTP Server. –  James Dec 2 '16 at 16:19      I had a lot of trouble getting this to work as I kept getting 404 errors. Turns out you may need to change the web.config to accept file names of the form {filename}.{extension}. See this Stackoverflow question for the details: stackoverflow.com/questions/20998816/… –  Simon Tewsi Jan 8 at 6:05

 | 

推荐:ASP.NET Web API

ASP.NET Web API includes support for the following features: Modern HTTP programming model: Directly access and manipulate HTTP requests and responses


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。