具有图像和正文的C#RESTful POST

时间:2018-06-20 02:45:06

标签: c# rest post xamarin.forms dotnet-httpclient

我当前正在尝试将一些数据发布到服务器以创建用户配置文件。 RESTful POST的正文选择了图像以及其他字段。

我设法使用邮递员将其张贴。但是,我试图弄清楚如何使用C#做到这一点。我尝试过,但似乎服务器返回状态500却没有太多有用的消息。

请参阅附件,了解我如何过帐到服务器以及有关如何尝试过帐的一些C#代码。感谢有关如何修复我的C#代码以使其正常工作的帮助。

enter image description here enter image description here

C#代码:

if (!string.IsNullOrEmpty(baseUrl) && !string.IsNullOrEmpty(apiKey))
        {
            var fullUrl = baseUrl + "/user_profiles";
            using (var httpClient = new HttpClient())
            {
                //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", apiKey);
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiKey);
                var boundary = "Upload----" + DateTime.Now.Ticks.ToString();

                using (var content = new MultipartFormDataContent(boundary))
                {
                    try
                    {
                        var name = string.IsNullOrEmpty(userRegistration.Name) ? "" : userRegistration.Name;
                        var city = string.IsNullOrEmpty(userRegistration.City) ? "" : userRegistration.City.ToUpper();
                        var phone = string.IsNullOrEmpty(userRegistration.Mobile) ? "" : userRegistration.Mobile;
                        phone = phone.Replace(" ", ""); //remove empty string in between and at edges
                        phone = phone.StartsWith("+") ? phone : "+" + phone;
                        var address = string.IsNullOrEmpty(userRegistration.CompanyAddress) ? "Unspecified" : userRegistration.CompanyAddress;
                        var country = string.IsNullOrEmpty(userRegistration.Country) ? "" : userRegistration.Country.ToUpper();
                        var email = string.IsNullOrEmpty(userRegistration.Email) ? "" : userRegistration.Email;
                        var isContractor = userRegistration.IsRegisteredAsContractor.ToString();
                        var category = string.IsNullOrEmpty(userRegistration.Category) ? "" : userRegistration.Category;
                        var companyName = string.IsNullOrEmpty(userRegistration.CompanyName) ? "" : userRegistration.CompanyName;
                        var companyAddress = string.IsNullOrEmpty(userRegistration.CompanyAddress) ? "" : userRegistration.CompanyAddress;

                        //TEST
                        //var body = new
                        //{
                        //    city,
                        //    phone,
                        //    address,
                        //    country,
                        //    email,
                        //    name,
                        //    identifier_for_vendor = localId,
                        //    is_contractor = isContractor,
                        //    work_categories = category,
                        //    company_name = companyName,
                        //    company_address = companyAddress
                        //};

                        //var bodyStr = JsonConvert.SerializeObject(body);
                        //var stringContent = new StringContent(bodyStr, Encoding.UTF8, "application/json");

                        //content.Add(stringContent);
                        //response = await httpClient.PostAsync(fullUrl, content).ConfigureAwait(false);
                        //TEST

                        content.Add(new StringContent(name, Encoding.UTF8, "text/plain"), "name");
                        content.Add(new StringContent(city, Encoding.UTF8, "text/plain"), "city");
                        content.Add(new StringContent(phone, Encoding.UTF8, "text/plain"), "phone");
                        content.Add(new StringContent(companyAddress, Encoding.UTF8, "text/plain"), "address");
                        content.Add(new StringContent(country, Encoding.UTF8, "text/plain"), "country");
                        content.Add(new StringContent(email, Encoding.UTF8, "text/plain"), "email");
                        content.Add(new StringContent(localId, Encoding.UTF8, "text/plain"), "identifier_for_vendor");
                        content.Add(new StringContent(isContractor, Encoding.UTF8, "text/plain"), "is_contractor");
                        content.Add(new StringContent(category, Encoding.UTF8, "text/plain"), "work_categories");
                        content.Add(new StringContent(companyName, Encoding.UTF8, "text/plain"), "company_name");
                        content.Add(new StringContent(companyAddress, Encoding.UTF8, "text/plain"), "company_address");

                        if (!string.IsNullOrEmpty(userRegistration.ProfileImagePath) && File.Exists(userRegistration.ProfileImagePath))
                        {
                            using (var stream = File.OpenRead(userRegistration.ProfileImagePath))
                            {
                                //stream.Seek(0, SeekOrigin.Begin);
                                var fileName = Guid.NewGuid().ToString() + ".jpg";
                                content.Add(new StreamContent(stream), "image", fileName);
                                response = await httpClient.PostAsync(fullUrl, content).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            response = await httpClient.PostAsync(fullUrl, content).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

使用File.OpenRead时,它将返回文件流(字节) 您需要将其转换为Base64,这是通过REST发送图像的首选方式。

base64Image = System.Convert.ToBase64String(stream);

之后,您将需要将其转换回后端,并将其存储在所需的任何位置。

此外,由于它有一些大小限制,因此我不建议您使用FormDataContent发送数据。

我建议使用JObject并添加要发送为JProperty的内容。

Uri postURL = new Uri(Constants.RestUrl + "/NewReservation");
HttpClient client = new HttpClient();
TimeSpan timeout = new TimeSpan(0, 0, 20);
client.Timeout = timeout;                   

var UserData = AccountCheck.CurrentUserData();

JObject RequestData = new JObject(
    new JProperty("apiKey", UserData.ApiKey),
    new JProperty("customerID", UserData.CustomerId.ToString()),
    new JProperty("containerIDs", NewReservationRequest.ContainerIDs),
    new JProperty("containersQuantities", NewReservationRequest.ContainerQuantities),
    new JProperty("location", NewReservationRequest.Location),
    new JProperty("image", NewReservationRequest.ImageBlob),
    new JProperty("dateFrom", NewReservationRequest.StartDate.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)),
    new JProperty("dateTo", NewReservationRequest.StartDate.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)),
    new JProperty("expectedTime",NewReservationRequest.ExpectedTime),
    new JProperty("remarks", UserRemarks)
                );


var RequestDataString = new StringContent(RequestData.ToString(), Encoding.UTF8, "application/json");

HttpResponseMessage responsePost = await client.PostAsync(postURL, RequestDataString);
string response = await responsePost.Content.ReadAsStringAsync();

之后,您将需要解析json响应。 如果您需要更多帮助,请回复此答案