Web API, C#, Json Objects, Views - json

I have some issues with displaying data as a Json object in this ASP.NET Web API project. It is my first try, I don't have Views, I am gonna use Postman for testing. Can you give me some diretions how to display the model as an Json Object?
//UserController
public class UsersController : ApiController
{
private LearnToLearnContext db = new LearnToLearnContext();
private BaseRepository<Users> _repository = null;
public UsersController()
{
this._repository = new BaseRepository<Users>();
}
// GET: api/Users
[ResponseType(typeof(Users))]
public IHttpActionResult GetUsers()
{
var user = _repository.GetAll();
var bindingModel = Mapper.Map<UsersBindingModels>(user);
return Ok(bindingModel);
}
}
//UserModel
public class Users
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Unique]
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public bool IsTeacher { get; set; }
public virtual List<Courses> Courses { get; set; }
}
//UserBindingModel
public class UsersBindingModels
{
[Required]
public string name { get; set; }
[Unique]
[Required]
public string email { get; set; }
[Required]
public string password { get; set; }
public bool isTeacher { get; set; }
public virtual List<Courses> Courses { get; set; }
}

Related

When i JsonConvert.DeserializeObject its just stops working in asp.net core

I'm trying to DeserializeObject my data to User class and when i do that, the method acts like nothing happend and finishing himself.
And that's my User class:
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string UserSurname { get; set; }
[Required, StringLength(50), DataType(DataType.EmailAddress)]
public string UserEMail { get; set; }
public string UserToken { get; set; }
public string UserPassword { get; set; }
public bool UserIsActive { get; set; }
public bool UserIsEmailConfirmed { get; set; }
}
Here it's my code :
firebaseClient = new FireSharp.FirebaseClient(firebaseConfig);
FirebaseResponse response = firebaseClient.Get("Users/");
User data = JsonConvert.DeserializeObject<User>(response.Body);//That's the point where i get the problem.
I'm working with Firebase,FireSharp and Asp.Net Core 5.0

Post Request gives a 405 error in Postman

on my .Net Web Api, I have an entity model, request model and response model for each database table. When i make a post request to MedTestOrder, i receive a 405 error, but other entities are working fine. I will post code snippets of MedTestOrder entity model, request model, response model, controller and service. The models contain foreign keys and I suspect my error could be from there. I might be wrong or not. I just need help.
1 - Entity Model
namespace Africanbiomedtests.Entities
{
public class MedTestOrder
{
[Key]
public int Id { get; set; }
public int? MedTestId { get; set; }
[ForeignKey("MedTestId")]
public MedTest MedTest { get; set; }
public int? healthcareProviderId { get; set; }
[ForeignKey("healthcareProviderId")]
public HealthcareProvider healthcareProvider { get; set; }
public int? accountId { get; set; }
[ForeignKey("accountId")]
public Account Account { get; set; }
public int? newbornId { get; set; }
[ForeignKey("newbornId")]
public Newborn Newborn { get; set; }
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateCompleted { get; set; }
public DateTime? Updated { get; set; }
}
}
2 - Api Request Model
namespace Africanbiomedtests.Models.MedTestsOrder
{
public class MedTestsOrderCreateRequest
{
[Required]
public MedTest MedTest { get; set; }
public HealthcareProvider healthcareProvider { get; set; }
public Account Account { get; set; }
public Newborn Newborn { get; set; }
[Required]
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
[Required]
public DateTime DateCreated { get; set; }
}
}
3 - Response Model
namespace Africanbiomedtests.Models.MedTestsOrder
{
public class MedTestsOrderResponse
{
public int Id { get; set; }
public MedTest MedTest { get; set; }
public HealthcareProvider healthcareProvider { get; set; }
public Account Account { get; set; }
public Newborn Newborn { get; set; }
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateCompleted { get; set; }
}
}
4 - Controller
[Authorize]
[HttpPost("create")]
public ActionResult<MedTestsOrderResponse> Create(MedTestsOrderCreateRequest model)
{
var medTestOrder = _medTestOrderService.Create(model);
return Ok(medTestOrder);
}
5 - Service
public MedTestsOrderResponse Create(MedTestsOrderCreateRequest model)
{
// map model to new account object
var medTestOrder = _mapper.Map<MedTestOrder>(model);
medTestOrder.DateCreated = DateTime.UtcNow;
// save account
_context.MedTestOrder.Add(medTestOrder);
_context.SaveChanges();
return _mapper.Map<MedTestsOrderResponse>(medTestOrder);
}
6 - Postman JSON request
{
"medTestId": 3,
"healthcareProviderId": 3,
"accountId": 1004,
"newbornId": 1,
"paymentStatus": "Complete Payment",
"completionStatus": "1",
"dateCompleted": "01/14/2021"
}
I would really appreciate any help right now
Thank you #Marius and #Karney, I realized i wasn't using the correct endpoint. I needed to add "/create" to my endpoint.
In some cases, your Web API method accepts only PUT requests, Try to put not post.

Object is always empty when deserialize on xamarin service

Have this service built on a xamarin app:
public class OpenWeatherMap<T>
{
private const string OpenWeatherApi = "http://api.openweathermap.org/data/2.5/weather?q=";
private const string Key = "653b1f0bf8a08686ac505ef6f05b94c2";
HttpClient _httpClient = new HttpClient();
// aqui podemos enviar directo a una ciudad hardcoded
public async Task<T> GetAllWeathers(string city)
{
var json = await _httpClient.GetStringAsync(OpenWeatherApi + city + "&APPID=" + Key);
var getWeatherModels = JsonConvert.DeserializeObject<T>(json);
return getWeatherModels;
}
}
When i check the model object is always empty. JSON is fine and my class matches perfectly my JSON model. I'm using Newtonsoft.Json.
This is my model:
public class WeatherMainModel
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("weather")]
public WeatherSubDetails[] Weather { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public string Visibility { get; set; }
[JsonProperty("wind")]
public WeatherWindDetails Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public string Dt { get; set; }
[JsonProperty("sys")]
public WeatherSysDetails Sys { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cod")]
public string Cod { get; set; }
}
public partial class Clouds // new
{
[JsonProperty("all")]
public string All { get; set; }
}
public partial class Coord // new
{
[JsonProperty("lon")]
public string Lon { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
}
public partial class Main
{
[JsonProperty("temp")]
public string Temp { get; set; }
[JsonProperty("pressure")]
public string Pressure { get; set; }
[JsonProperty("humidity")]
public string Humidity { get; set; }
[JsonProperty("temp_min")]
public string TempMin { get; set; }
[JsonProperty("temp_max")]
public string TempMax { get; set; }
}
public partial class WeatherSysDetails
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public string Sunrise { get; set; }
[JsonProperty("sunset")]
public string Sunset { get; set; }
}
public partial class WeatherSubDetails
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public partial class WeatherWindDetails
{
[JsonProperty("speed")]
public string Speed { get; set; }
[JsonProperty("deg")]
public string Deg { get; set; }
}
I'm using visual studio community set for Latin America (Chile), so i tried changing every decimal field on the JSON to string on the model to avoid comma separation problems, but still, my object is coming empty no matter the JSON i inject to the deserializer.
Thanks in advance.

I am a new bee with JSON and I don't know how to perform serialization and deserialization in windows phone

get links will be like this - http//192.156.120.192/Projects/cricket/index.php/api/api
public class Player
{
public int playerId { get; set; }
public string playerName { get; set; }
public string specialization { get; set; }
public string battingHand { get; set; }
public string bowlingHand { get; set; }
public string bowlingType { get; set; }
public object genericId { get; set; }
public int homeTeamId { get; set; }
public int eligibleTeams { get; set; }
public object imageUrl { get; set; }
}
public class RootObject
{
public string methodName { get; set; }
public int errorCode { get; set; }
public string errorMessage { get; set; }
public List<Player> players { get; set; }
}
I am using Json.NET and it is super easy
// create a RootObject object
//..
string serializedRoot = JsonConvert.SerializeObject(myRootObject);
RootObject deserializedRoot = JsonConvert.DeserializeObject<Player>(serializedRoot);

Attempt to access the method failed: System.Collections.Generic.List`1..ctor()

I've this code through which I am retrieveing json data from my Localhost.But it is giving the error mentioned in my title.When I hover over the response while debugging.It shows me the correct response.I am using JSON.NET to parse json response.
var response = reader.ReadToEnd();
List<Company> cLst = JsonConvert.DeserializeObject<List<Company>>(response); //Error
this.Dispatcher.BeginInvoke(() =>
{
foreach (Company c in cLst)
{
ListBoxItemControl Li = new ListBoxItemControl();
Li.CompanyNameTextBlock.Text = c.CompanyName;
Li.PromotionTextBlock.Text = c.PromotionText;
listBox1.Items.Add(Li);
}
});
Here is the Company Class.
class Company
{
public string CompanyName {get; set;}
public string CompanySlogan { get; set; }
public string CompanyDescription { get; set; }
public string CompanyRating { get; set; }
public string CompanyDpPath { get; set; }
public string CompanyOtherInfo { get; set; }
public string CompanyFollowers { get; set; }
public int CompanyID { get; set; }
public int PromotionID { get; set; }
public string PromotionText { get; set; }
public string PromotionRating { get; set; }
public string PromotionPicPath { get; set; }
public string PromotionTitle { get; set; }
public int PromotionLikes { get; set; }
public int PromotionComments { get; set; }
}
Try making the Company class public
Take another class like,
public class RootObject
{
public List<Company> companies;
}
And then modify your code like this,
var jsonData = JsonConvert.DeserializeObject<RootObject>(response);
List<Company> cLst = jsonData.companies;
Try this and let me know.