I am trying to write a c# code by which I want to get a image from web api and the title of the image from the api. I implemented a method named GetImage and try to return two results (image and title) from it. However I wrote a code but as I am new handling this situation,I do not know what to do in this case.
My Image service class which contain the methods is-
public class ImageService
{
public string GetImage(string name)
{
string result1;
string result2;
using (WebClient client = new WebClient())
{
var uri = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&pithumbsize=400&titles="+name;
string requestUrl = string.Format(uri, name);
var response = client.DownloadString(new Uri(uri));
var responseJson = JsonConvert.DeserializeObject<ImgRootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
result1 = responseJson.query.pages[firstKey].thumbnail.source;
result2 = responseJson.query.pages[firstKey].title;
var hash = uri.GetHashCode();
}
return result1,result2; //showing error
}
}
Now the Form1.cs where i want to show results in picturebox and label is-
public partial class Form1 : Form
{
private readonly ImageService _imageService;
public Form1()
{
_imageService = new ImageService();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.LoadAsync(_imageService.GetImage(textBox1.Text));
label1.Text = _imageService.GetImage(textBox1.Text);// not working
}
}
The best method is to create a new class that holds the details you need and return that. That way, if you need to add more information, you can just add it to the class.
For example:
public class ImageInfo
{
public string Title { get; set; }
public string Image { get; set; }
}
Then your method returns the class:
public ImageInfo GetImage(string name)
{
ImageInfo info = new ImageInfo();
using (WebClient client = new WebClient())
{
var uri = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&pithumbsize=400&titles="+name;
string requestUrl = string.Format(uri, name);
var response = client.DownloadString(new Uri(uri));
var responseJson = JsonConvert.DeserializeObject<ImgRootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
info.Image = responseJson.query.pages[firstKey].thumbnail.source;
info.Title = responseJson.query.pages[firstKey].title;
var hash = uri.GetHashCode();
}
return info;
}