Как разместить файлы формы данных с C # на внешний API - PullRequest
0 голосов
/ 21 октября 2019

Я создал API с ядром asp.net, которое должно принимать POST файлов и строк. API прекрасно работает с Postman, но я не уверен, как реализовать действие POST от Postman до моего Asp. net Client.

[HttpPost]
    public async Task<IActionResult> PostAttachment([FromForm] Attachment attachment)
    {            
        if (attachment.Files == null)
        {
            return BadRequest("File is required");
        }

        foreach (var file in attachment.Files)
        {
            if (file != null)
            {
                var extension = Path.GetExtension(file.FileName);
                var allowedExtensions = new[] { ".jpg", ".png", ".docx", ".pdf", ".xlsx" };

                if (!allowedExtensions.Contains(extension.ToLower()))
                {
                    return BadRequest("Only the follwing extentions are allowed: .jpg, .png, .docx, .pdf, .xlsx");
                }

                if (file.Length > 5300000)
                {
                    return BadRequest("File size should be less than 5MB");
                }

                var upload = _hostingEnvironment.ContentRootPath + "\\uploads";

                for (int i = 0; i < attachment.Files.Count; i++)
                {
                    var filePath = Path.Combine(upload, file.FileName);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                        attachment.Path = file.FileName;
                    }
                }
            }
        }

            _context.Attachments.Add(attachment);
            await _context.SaveChangesAsync();

            return Content("Upload Successful.");          

    }

А это моя модель вложения

public class Attachment
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    [Required]
    public string Path { get; set; }
    public DateTime UploadDate { get; set; }

    public Request Request { get; set; }
    public int RequestId { get; set; }

    [NotMappedAttribute]
    public List<IFormFile> Files { get; set; }
}

В Почтальоне я делаю следующее: Почтальон

и все работаетотлично.

Я хочу знать, как я могу сделать то же самое, что и Postman, но на моем клиенте asp.net.

Я уже попробовал фрагмент кода, который почтальон предоставляет с RestSharp, но я получаюфайлы, загруженные с 0 байтами:

var client = new RestClient("https://localhost:44316/api/Attachments");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "4097");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Content-Type", "multipart/form-data; boundary=--------------------------938323281300032110502154");
request.AddHeader("Host", "localhost:44316");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.16.3");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"Files\"; filename=\"lang.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"Files\"; filename=\"uk.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"Path\"\r\n\r\nstring path\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"RequestId\"\r\n\r\n8\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

. , ОБНОВЛЕНИЕ 1:

Я попытался удалить параметр из предыдущего кода и добавить его:

request.AddFile("Files", "C:/Users/User/Desktop/First-app/VisitorPortalImgs/Picture2.png", "image/png");
        request.AddFile("Files", "C:/Users/User/Desktop/First-app/VisitorPortalImgs/Picture1.png", "image/png");
        request.AddFile("Files", "C:/Users/User/Desktop/First-app/VisitorPortalImgs/Picture1.png", "image/png");
        request.AddParameter("Path", "Picture1path.png");
        request.AddParameter("UploadDate", "10/21/2019 11:11 AM");
        request.AddParameter("RequestId", "9");
        request.AlwaysMultipartFormData = true;

На этот раз ничего не загружается в API.

...