0

I have an enpoint that I send request via Postman form-data. Request has 2 keys.

message : string
file: File

this works ok. So, I want to send the same request in C# code. In c# I just need to choose file from local, somehow convert it to proper format, assign it to file property in request Model, I mean I can not change the logic how request is sent. I must not write additional logic to HttpRequest or MultipartFormDataContent etc (I can not even see this part how it is sent). Just need to add Model to this request body. I have model RequestModel

public class RequestModel
{
[JsonProperty("message")]
public string Message {get; set; }

[JsonProperty("file")]
public whateverType File {get; set; }
}

message part works, so I need to assign local file to File property. how can I do that. I tried almost everything but it does not work. Thanks.

  • .Net Core or .net Framwork? – Neil Feb 05 '22 at 16:54
  • Does this answer your question? [How to upload files in asp.net core?](https://stackoverflow.com/questions/35379309/how-to-upload-files-in-asp-net-core) – Neil Feb 05 '22 at 16:54
  • This SO thread is similar for asp.net core: https://stackoverflow.com/questions/54411250/how-to-send-multipart-form-data-to-asp-net-core-web-api – Steve Wong Feb 05 '22 at 16:57
  • in .net 6. these answers do not solve my problem. simply I need to convert the way postman converts. when i choose file in postman how it converts this file? what is the equivalent of converted type in c#? – sultanriveriere Feb 05 '22 at 17:09

1 Answers1

0

You don't need to keep the file in your model.

this is an example to post a model just by knowing the file name.

var model = new RequestModel();

// ... fill the model with some data
model.Message = "test";
model.File = @"c:\test.jpg";

using var httpClient = new HttpClient();
{
    var form = new MultipartFormDataContent();
    form.Add(new StringContent(model.Message), nameof(RequestModel.Message));

    var bytes = File.ReadAllBytes(model.File);
    form.Add(new ByteArrayContent(bytes, 0, bytes.Length), "profile_pic", "hello1.jpg");
    var response = await httpClient.PostAsync("PostUrl", form);
    response.EnsureSuccessStatusCode();
    var sd = response.Content.ReadAsStringAsync().Result; // you should use await if your method is async ...
}

public class RequestModel
{
    public string Message { get; set; }

    public string File { get; set; } // simply use file-path
}
AliReza Sabouri
  • 4,355
  • 2
  • 25
  • 37