Passing Date in an API - datetime

I am working on .Net Core and want to post attributes in the api containing dates but I m not able to handle dates for an API. How to overcome with this error.
using System;
using System.Collections.Generic;
namespace Server.Dtos
{
public class ProjectSessionDto
{
public int Id { get; set; }
public string Activity { get; set; }
public string ResourcePerson { get; set; }
public DateTime? TentativeDate { get; set; }
public DateTime SubmissionDate { get; set; }
public int SemesterId { get; set; }
public string Program { get; set; }
public string Batch { get; set; }
}
}
Controller Code...
[HttpPost("addprojectsession")] //Since there would be 2 Post Methods. Login and Register
public async Task<IActionResult> AddProjectSession(ProjectSessionDto projectsession)
{
var semester = await _semester.GetSemesterWithProjectSession(projectsession.SemesterId);
semester.projectsessions.Add(_mapper.Map<ProjectSessionDto,ProjectSession>(projectsession));
await _semester.AddSemesterWithProject(semester);
return Ok();
}
}

There are two issues you need to fix :
In Postman ,change the values with double quotes:
"tentativeDate": "12/12/2019",
"SubmissionDate":"12/12/2019"
In controller , use [FromBody]to make asp.net core model binding wokring for reading value from request body :
public async Task<IActionResult> AddProjectSession([FromBody]ProjectSessionDto projectsession)

Related

Bind route parameter & values from json body to the model

I have a put API in .net core 3.1 Web API project.
URL: https://localhost:44319/api/user/4
Controller method:
[HttpPut("{id}")]
[ProducesResponseType(typeof(UpdateUserCommandResponse), StatusCodes.Status200OK)]
public async Task<ActionResult<UpdateUserCommandResponse>> PutUser(UpdateUserCommand updateUserCommand)
{}
UpdateUserCommand model:
public class UpdateUserCommand : IRequest<UpdateUserCommandResponse>
{
[FromRoute(Name = "id")]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Is it possible to populate Id in model from the URL & rest of the fields from the json body? Right now, Id remain 0
I would also like to not include the attribute right in the model, since the same
--- Updated Code -----
[HttpPut("{id}")]
[ProducesResponseType(typeof(UpdateUserCommandResponse), StatusCodes.Status200OK)]
public async Task<ActionResult<UpdateUserCommandResponse>> PutUser(UpdateUserCommand updateUserCommand)
{
var response = await _mediator.Send(updateUserCommand);
return Ok(response);
}
public class UpdateUserCommand : IRequest<UpdateUserCommandResponse>
{
//[FromRoute]
public int Id { get; set; }
[FromForm]
public string FirstName { get; set; }
[FromForm]
}
It will be working properly without any attributes at all if you select Content-Type
application/x-www-form-urlencoded
//or
multipart/form-data
or if you still have some problem you can try this
public int Id { get; set; }
[FromForm]
public string FirstName { get; set; }
[FromForm]
public string LastName { get; set; }
if you select Content-Type
application/json
you will have to change your action
[HttpPut("{id}")]
... PutUser( int id, [FromBody] UpdateUserCommand updateUserCommand)
{}
and IMHO remove [ProducesResponseType(typeof(UpdateUserCommandResponse), StatusCodes.Status200OK)] . I can't see what do you need it for

JsonConvert.DeserializeObject<> is returning null last childtoken of the two childrentokens

I am sending a JObject from the frontend to my API, which is divided into First and Last childtokens, as seen in the picture below:
However, when I am trying to use the following code, the last part of childrendtoken is becoming null
var RVoucher = JsonConvert.DeserializeObject<VMReceive>(request.ToString());
This is what I am having in the debugging mode:
Here, the VMReceive is a viewModel that consists of another viewmodel "VMMonth"and an ado.net generated model class "ReceiveVoucher".
Code of the models are given below:
public class VMReceive
{
public List<VMMonth> Month { get; set; }
public ReceiveVoucher receiveVoucher { get; set; }
}
public class VMMonth
{
public int item_id { get; set; }
public string item_text { get; set; }
}
public partial class ReceiveVoucher
{
public int ReceiveVoucherId { get; set; }
public Nullable<int> MonthId { get; set; }
public string ReceivedBy { get; set; }
public string Remarks { get; set; }
public Nullable<int> ReceivedAmount { get; set; }
}
I have also tried putting [JsonProperty("")] over each property of my "ReceiveVoucher" model class, but got the same 'null' issue.
I am not sure about what I am doing wrong here, your suggestion regarding this will be very helpful.
Your JSON property name doesn't match. Your class uses receiveVoucher whereas the JSON is ReceiveAmount. Also, why are you using JObject in the first place, this should work by just using the class name as the action parameter:
public HttpResponse PostReceive([FromBody] VMReceive RVoucher, int userId)
{
...
}

Http 500 Internal Server Error on POST Request

I'm trying to send data to server with POST method but I got 500 Internal Server Error. Here's my codes. What do I need to fix this? Thank you.
Rest API POST Method
public void Post([FromBody]OrderLineTerminalViewModel[] OrderLineItems)
{
foreach (var OrderLineItem in OrderLineItems)
{
…………
}
_context.SaveChanges();
}
MODEL
public class OrderLineTerminalViewModel
{
public int Id { get; set; }
public string Unit { get; set; }
public decimal Qtty { get; set; }
public int ReferanceNumberId { get; set; }
}
SAMPLE JSON
[ {'Id':73039,'Unit':'PCS','Qtty':33.0,'ReferanceNumberId':20041},
{'Id':73040,'Unit':'PC','Qtty':120.0,'ReferanceNumberId':20041}]
Please check my API which is working completely fine(Tested).
Note:-
Add HttpPost before API method and remove [FromBody].
[RoutePrefix("api")]
public class ValuesController : ApiController
{
[HttpPost]
[Route("postrequest")]
public void Post(OrderLineTerminalViewModel[] OrderLineItems)
{
//your Code
}
}
Model:
public class OrderLineTerminalViewModel
{
public int Id { get; set; }
public string Unit { get; set; }
public decimal Qtty { get; set; }
public int ReferanceNumberId { get; set; }
}
Json:-
[ {"Id":73039,"Unit":"PCS","Qtty":33.0,"ReferanceNumberId":20041},
{"Id":73040,"Unit":"PC","Qtty":120.0,"ReferanceNumberId":20041}]
Tested

AspNet EF6 - Entity type has no key defined

So I changed up my databases and remade them. I followed the EF6 tutorial but encountered this error when trying to create a controller with views. I did some research on the error and people said to add data annotations and I tried [Key] but I keep getting the same error. Not sure if i've forgotten anything? Thanks!
"There was an error running the selected code generator: 'Unable to retrieve metadata for 'LinkDB.Models.Identifier.' Unable to determine the principal end of an association between the type 'LinkDB.Models.Identifier' and 'LinkDB.Models.Identity'. The principal end of this association must be explicity configured using either the relationship fluent API or data annotation.'
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace LinksDB.Models
{
public class Identity
{
[Key]
public int ID { get; set; }
public int IdentifierID { get; set; }
public string contact { get; set; }
public string contactname { get; set; }
public string price { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual Identifier Identifiers { get; set; }
public virtual Metric Metrics { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace LinksDB.Models
{
public class Identifier
{
[Key]
public int ID { get; set; }
public string domain { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual Identity Identitys { get; set; }
public virtual Metric Metrics { get; set; }
}
}
using LinksDB.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace LinksDB.DAL
{
public class LinkData : DbContext
{
public LinkData() : base("LinkData")
{
}
public DbSet<Identifier> Identifiers { get; set; }
public DbSet<Identity> Identitys { get; set; }
public DbSet<Link> Links { get; set; }
public DbSet<Metric> Metrics { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
OK, if you want a 1:1 relationship between Identity and Identifier those models should look like below where the child (Indentifier) uses the IdentityId as both it's PK and FK. You can also do this with fluent code. Start with this and then add in your Metric and Links relationships.
public class Identity
{
[Key]
public int ID { get; set; }
public string contact { get; set; }
public string contactname { get; set; }
public string price { get; set; }
public virtual Identifier Identifier { get; set; }
}
public class Identifier
{
[Key, ForeignKey("Identity")]
public int IdentityID { get; set; }
public string domain { get; set; }
public virtual Identity Identity { get; set; }
}
Example here

asp.net json .net objects

I have this class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestConnect
{
public class UserInfo
{
public string id { get; set; }
public string name { get; set; }
public string picture { get; set; }
public string bio { get; set; }
public string quotes { get; set; }
//public HometownInfo from { get; set;
public From hometown { get; set; }
public string relationship { get; set; }
public string gender { get; set; }
public List<Education> data { get; set; }
}
public class Education
{
public From school { get; set; }
public From year { get; set; }
//public From [] concentration { get; set; }
public string type { get; set; }
}
}
public class HometownInfo
{
public string id { get; set; }
public string homename { get; set; }
}
Now trying to do
url = "https://graph.facebook.com/me?fields=education&access_token=" + oAuth.Token;
json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty);
Education edu = js.Deserialize<Education>(json);
foreach(Education_history edu_history in Education.data) gives an error
Object reference not set to an
instance of an object. Description: An
unhandled exception occurred during
the execution of the current web
request
Thanks
User
Have you tried setting breakpoints at the various steps in your code and seeing where it might be?
somewhere else in your code you must be declaring url and json?
does js.Deserialize() create a new object or are you missing this
Education edu = new Education();
Also if its in a web application make sure that your code is placed in the correct page events so that they happen in the correct order

Resources