I've developed an ASP.NET web API which is actually retrieving data from a Fake API But When I'm reading data and from my API controller trying to call that Data Service Function then always my browser showing data in xml format but I want to show it in JSON format.
Here is my code:
Data Service Function:
public List<UserModel> GetData()
{
var list = new List<UserModel>();
var url = "http://jsonplaceholder.typicode.com/posts";
String json = string.Empty;
try
{
HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.ContentType = "application/json; charset=utf-8";
using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
Stream stream = response.GetResponseStream();
StreamReader re = new StreamReader(stream);
json = re.ReadToEnd();
json = "{\"Users\":" + json + "}";
JsonSerializer serializer = new JsonSerializer();
wrapper w = JsonConvert.DeserializeObject<wrapper>(json);
list = w.UserDetails;
}
}
}
catch (Exception ex)
{
throw (ex);
// ShowError(ex);
// if the server returns a 500 error than the webRequest.GetResponse() method
// throws an exception and all I get is "The remote server returned an error: (500)."
}
return list;
}
Controller:
[HttpGet]
public IEnumerable<UserModel> GetAllUsers()
{
try
{
DataService ds = new DataService();
return ds.GetData();
}
catch (Exception ex)
{
throw (ex);
}
}
My output coming as this into the browser:
Please help on the above. Thanks on advance.