Как опубликовать изображение из xamrine в webapi в asp.net mvc

#c# #asp.net-mvc #asp.net-web-api #xamarin.forms #steam-web-api

#c# #asp.net-mvc #asp.net-web-api #xamarin.forms #steam-веб-api

Вопрос:

Вот мой правильный код webapi, я проверяю, что отправляю изображение с помощью postman .. как отправить изображение в webapi, сохранение изображения уже работает. но мне нужно, как отправить изображение из xamrine в запрос webapi.

 [HttpPost]
public ActionResult PostData([System.Web.Http.FromBody] string Name,HttpPostedFileBase Picture)
{
    ResponseModel response = new ResponseModel();
    try
    {
        //using (AndroidApiPostEntities db = new AndroidApiPostEntities())
        //{
            Dictionary<dynamic, dynamic> dic = new Dictionary<dynamic, dynamic>();
            string img = "";
            img = ImageUpload(Picture);
            PostPicture p = new PostPicture();
            p.Name = Name;
            p.Picture = img;
            //db.PostPictures.Add(p);
            //db.SaveChanges();
            response.error = false;
            response.message = "data added successfully.";

            dic.Add("Id", 0);
            dic.Add("Name", p.Name);
            dic.Add("Picture", p.Picture);
            response.data = dic;

            return Json(response, JsonRequestBehavior.AllowGet);
        //}
    }
    catch (Exception ex)
    {
        response.error = true;
        response.message = "inner exp: "   ex.InnerException.Message   " /second/: "   Convert.ToString(ex.InnerException);
        return Json(response, JsonRequestBehavior.AllowGet);
    }
}

private string ImageUpload(HttpPostedFileBase img)
{
    string fileName;
    string extension = System.IO.Path.GetExtension(img.FileName);
    Random rnd = new Random();

    fileName = "b"   rnd.Next(1000).ToString("000")   extension; //Create a new Name for the file due to security reasons.

    // string fileName = Guid.NewGuid().ToString()   ImageName;

    //var path = Path.Combine(Directory.GetCurrentDirectory(), "images", fileName);

    //string fileName = Guid.NewGuid().ToString()   ImageName;
    string physicalPath = Server.MapPath("/images/"   fileName);
    //string physicalPath = "~/images/"   fileName;

    // save image in folder
    img.SaveAs(physicalPath);
    return fileName;
}
  

Теперь вот мой код нажатия кнопки xamrine, как опубликовать изображение или как преобразовать изображение для его публикации, также нажмите api, вот код, но я сталкиваюсь с ошибкой изображения, я сталкиваюсь с нулевым изображением в webapi

 private async void btnsubmit_Clicked(object sender, EventArgs e)
{
    try
    {
        string picc = MyImage.Source.ToString();


         PostUserAsync(txtName.Text, "");

    }
    catch (Exception ex)
    {
       await DisplayAlert("Error", ex.InnerException.ToString(), "OK");
    }
}

static MediaFile files;

public async void PostUserAsync(string name, string pic)
{
    string Host = "http://dxxx5.expxxxxxxxion.com/Home/PostData";
    var client = new HttpClient();
    var ss=MyImage.Source = ImageSource.FromStream(() =>
    {
       var stream = files.GetStream();
        return stream;
    });



    byte[] file = File.ReadAllBytes(files.Path);
    WebClient webClient = new WebClient();
    var fileData = webClient.Encoding.GetString(file);
    var fileName = System.IO.Path.GetFileNameWithoutExtension(files.Path);

    var model = new PostPicture
    {
        Name = name,
        Picture = file
    };

    var json = JsonConvert.SerializeObject(model);

    HttpContent httpContent = new StringContent(json);

    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var response = client.PostAsync(Host, httpContent).Resu<
    string res = "";
    using (HttpContent content = response.Content)
    {
        // ... Read the string.
        Task<string> result = content.ReadAsStringAsync();
        res = result.Resu<
    }
    var jsoss = JsonConvert.DeserializeObject(res);
    //var rootObj = JsonConvert.DeserializeObject<PostPicture>(File.ReadAllText(res));
    string f = jsoss.ToString();

    await DisplayAlert("Successfull", f, "OK");

}
  

Комментарии:

1. PostUserAsync является async . Вы должны использовать не Task.Result для получения результатов другие асинхронные методы, а await их!

2. Вы уверены, что файл должен быть размещен в формате JSON? Если да, сравнивали ли вы JSON, отправленный через Postman, и тот, который создан из вашего приложения? Как выглядит ваш запрос Postman?

3. Кроме того, я не вижу, где files назначено. Так ли это?

4. ilclubdellesei.blog/2018/02/14/…