簡體   English   中英

如何在 C# Web API 中發布 IFormFile?

[英]How to post IFormFile in C# Web API?

我在 C# 中創建了一個 web api,其中一種操作方法將對象作為參數,其中包括 IFormFile 並發送文件進行打印。 但是每次我使用一些 c# 控制台應用程序調用這個函數時,我都會得到這個 IFormFile 為空。

這是我的 API 代碼:

    [Route("print")]
    [HttpPost]
    public IHttpActionResult Print([FromBody] PrintFile printDocument)
    {
        try
        {
            if (ModelState.IsValid)
            {

                var response = _printingService.PrintFile(printDocument.Document, printDocument.PrinterName, printDocument.ServerName);

                 return Ok(response);

             }
             else
             {
                 return Unauthorized();
             }

        }
        catch (Exception ex)
        {
            return BadRequest(string.Format(ErrorMessages.GeneralErrorMsg, ex.Message));
        }
    }

模型類:

public class PrintFile
{
    public string PrinterName { get; set; }

    public string ServerName { get; set; }

    [Required]
    public IFormFile File { get; set; }

    public IDictionary<string, string> Parameters { get; set; }
}

調用此 API 方法的 C# 客戶端應用程序:

    public ResponseData PrintFile(PrintFileInfo printFileInfo)
    {
        try
        {
            _request = new RestRequest(ResourceNames.Print, Method.POST);                
            _request.AddJsonBody(printFileInfo);

            var response = _client.Execute(_request);

            var responseData = new ResponseData()
            {
                ResponseCode = response.StatusCode.ToString(),
                ResponseBody = response.Content
            };

            return responseData;
        }
        catch (Exception ex)
        {
            _logger.Error(ex, string.Format(ErrorMessages.ResourceException, ResourceNames.Print));

            throw;
        }
    }

通過這個 C# 客戶端發送時,我可以看到 IFormFile 填充了數據,但是當它進入 API 時,它變為空。 任何建議將不勝感激。

我不認為你可以發布這樣的 IFormFile; 我相信它必須是 action 方法的參數,而不是參數的屬性。 如果您確實需要使用復雜的參數,最好將整個文件加載到該屬性中,作為字節數組或字符串。

您使用 FromBody 屬性,但您需要使用 FromForm

[Route("print")]
        [HttpPost]
        public IHttpActionResult Print([FromForm] PrintFile printDocument)
        {
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM