3

ASP.Net Web API のコントローラーに POST されたアップロードされたファイルを同期的に処理する方法はありますか?

Microsoft が提案したプロセスhereを試してみましたが、説明どおりに動作しますが、RESTful API の残りの部分と一致させるために、Controller メソッドから Task<> 以外のものを返したいと思います。

基本的に、これを機能させる方法があるかどうか疑問に思っています:

public MyMugshotClass PostNewMugshot(MugshotData data){
    //get the POSTed file from the mime/multipart stream <--can't figure this out
    //save the file somewhere
    //Update database with other data that was POSTed
    //return a response
}

繰り返しますが、非同期の例を機能させましたが、クライアントに応答する前にアップロードされたファイルを処理する方法を望んでいます。

4

1 に答える 1

1
public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var appData = HostingEnvironment.MapPath("~/App_Data");
        var folder = Path.Combine(appData, Guid.NewGuid().ToString());
        Directory.CreateDirectory(folder);
        var provider = new MultipartFormDataStreamProvider(folder);
        var result = await Request.Content.ReadAsMultipartAsync(provider);
        if (result.FileData.Count < 1)
        {
            // no files were uploaded at all
            // TODO: here you could return an error message to the client if you want
        }

        // at this stage all files that were uploaded by the user will be
        // stored inside the folder we specified without us needing to do
        // any additional steps

        // we can now read some additional FormData
        string caption = result.FormData["caption"];

        // TODO: update your database with the other data that was posted

        return Request.CreateResponse(HttpStatusCode.OK, "thanks for uploading");
    }
}

アップロードされたファイルは、次のような名前で指定されたフォルダー内に保存されていることに気付くかもしれません: BodyPart_beddf4a5-04c9-4376-974e-4e32952426ab. これは Web API チームが意図的に選択したものであり、必要に応じてオーバーライドできます。

于 2012-08-28T18:26:57.443 に答える