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.
Related
I have a json string in my controller. When i deserialize that into my model, it's returning a null value. The very strange part here is that this was working a while ago then stopped. Any thoughts as to what's wrong here? This is an api call, so i don't have the luxury of changing the json either. tCustLst is the problem child that is returning null from the model.
json (result):
"{\"response\":{\"cErrorMessage\":\"\",\"moreRecordsAvailable\":false,\"tCustLst\":{\"t-custLst\":[{\"custNo\":324161.0,\"shipTo\":\"\",\"name\":\"TEST \\/ (NICKNAME)\",\"addr1\":\"P.O. BOX 111\",\"addr2\":\"\",\"city\":\"NYC\",\"state\":\"NY\",\"zipCd\":\"55555-1234\",\"ordBal\":0.0,\"totalBal\":20451.67,\"sortFld\":\" 123456\"}]}}}"
controller code:
CustomerList.Rootobject records = JsonConvert.DeserializeObject<CustomerList.Rootobject>(result);
return View(records);
model:
using Newtonsoft.Json;
using System.Collections.Generic;
namespace WebappsIntranet.Models
{
public class CustomerList
{
public class Rootobject
{
public string cErrorMessage { get; set; }
public bool moreRecordsAvailable { get; set; }
public tCustLst tCustList { get; set; }
}
public class tCustLst
{
[JsonProperty("t-custLst")]
public List<tCustcomerList> tcustomerlist { get; set; }
}
public class tCustcomerList {
public float custNo { get; set; }
public string shipTo { get; set; }
public string name { get; set; }
public string addr1 { get; set; }
public string addr2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zipCd { get; set; }
public float ordBal { get; set; }
public float totalBal { get; set; }
public string sortFld { get; set; }
}
}
}
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; }
}
I have been looking for ages and found some similar questions but no answers which fixed my issue.
I have recently developed a Web API project with seperate server side and client side code. I am wanting to do some testing through apiary, mainly for posting data. This requires me to have a "sample" of the posted JSON. However i cannot seem to get a working sample (I am using Postman to test the JSON).
I am sending a ViewModel:
public class ExampleViewModel
{
public ExampleModel exampleModel { get; set; }
public String[] strings { get; set; }
}
With the model:
public class ExampleModel
{
public long ID { get; set; }
public string User { get; set; }
public string Title { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public bool Recieved { get; set; }
public bool CompleteRemotly { get; set; }
public bool CompleteInField { get; set; }
public string Email { get; set; }
public Nullable<DateTime> RecievedDate { get; set; }
public Nullable<DateTime> ScheduledFor { get; set; }
public Nullable<DateTime> CompleteOn { get; set; }
public string Priority { get; set; }
public string DiagnosticReports { get; set; }
public string CReference { get; set; }
public string JReference { get; set; }
}
The format the POST is expecting is:
Key: "evm",
Value: {APIProject.ViewModels.ExampleViewModel}
And:
APIProject.ViewModels.ExampleViewModel:
{
strings = [""],
exampleModel = {ExampleModel}
}
My latest attempt is:
{
"evm":{
"ExampleViewModel":{
"exampleModel":{
"ID":0,
"User":"Harrison",
"Title":"Other",
"Type":"Other",
"Description":"ygfvgufuf",
"Recieved":true,
"CompleteRemotly":false,
"CompleteInField":false,
"Email":null,
"RecievedDate":"\/Date(1458133155546)\/",
"ScheduledFor":null,
"CompleteOn":null,
"Priority":"Low",
"DiagnosticReports":null,
"CPA_Reference":null,
"Jira_Reference":null,
"strings":[]
},
"strings":[""]
}
}
}
Which returns:
Key: "evm",
Value: {APIProject.ViewModels.ExampleViewModel}
And:
APIProject.ViewModels.ExampleViewModel:
{
strings = null,
exampleModel = null
}
So i got this to work by sending the following JSON, I guess i was over complicating the situation.
{
"requestManagements":{
"RequestID":0,
"User":"Harrison",
"RequestTitle":"Other",
"RequestType":"Other",
"RequestDescription":"ygfvgufuf",
"RequestRecieved":true,
"RequestCompleteRemotly":false,
"RequestCompleteInField":false,
"Email":null,
"RequestRecievedDate":"\/Date(1458133155546)\/",
"ScheduledFor":null,
"CompleteOn":null,
"Priority":"Low",
"DiagnosticReports":null,
"CPA_Reference":null,
"Jira_Reference":null,
"RequestManagerImages":[]
},
"images":[""]
}
i have a report where i display some subclasses values. It's working well for some, but not for others and i don't know why. The models :
[Serializable]
public partial class CompanyProvider
{
public int CompanyProviderId { get; set; }
public string CompanyNo { get; set; }
public string LPID { get; set; }
public string VATNo { get; set; }
public int? CompanyProviderAddressId { get; set; }
[ForeignKey("CompanyProviderAddressId")]
public virtual CompanyProviderAddress CompanyProviderAddress { get; set; }
public int? CompanyProviderAddressBillingId { get; set; }
[ForeignKey("CompanyProviderAddressBillingId")]
public virtual CompanyProviderAddressBilling CompanyProviderAddressBilling { get; set; }
public int? CompanyProviderContactManagerId { get; set; }
[ForeignKey("CompanyProviderContactManagerId")]
public virtual CompanyProviderContactManager CompanyProviderContactManager { get; set; }
public int? CompanyProviderBankId { get; set; }
[ForeignKey("CompanyProviderBankId")]
public virtual CompanyProviderBank CompanyProviderBank { get; set; }
...
}
[Serializable]
public partial class CompanyProviderBank
{
public int CompanyProviderBankId { get; set; }
public int? BankId { get; set; }
public virtual Bank Bank { get; set; }
public string Postcode { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
}
[Serializable]
public partial class CompanyProviderAddress
{
public int CompanyProviderAddressId { get; set; }
public string Postcode { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
}
It's working for CompanyProviderAddress and CompanyProviderAddress which have only "simple" properties (string, int...), but it doesn't work for CompanyProviderContactManager and CompanyProviderBank which have complex properties (like Bank for CompanyProviderBank).
Everything is serializable, this is working in my report :
=First(Fields!CompanyProviderAddress.Value.City(), "CompPro")
But this doesn't works, give me an #Error
=First(Fields!CompanyProviderBank.Value.City(), "CompPro")
Any idea? Or maybe someone knows how to get more details about #error, something more explicit?
Thx
It is possible your objects are null.
You can check if they are null like this:
=IIF(IsNothing(First(Fields!CompanyProviderBank.Value.City)), 0,First(Fields!CompanyProviderBank.Value.City))
I'm not entirely sure the above is in the correct syntax, please let me know if it isn't.
I have an MVC 4 application that is using code first to generate tables and columns in my SQL Server DB. I am trying to figure out how I ended up with an additional TABLE that was not intended. I have looked through some questions but not found the exact same problem I am having. I will try to explain this simply.
I have added a model called Associate which keeps track of associates that my client does business with. Each Associate needs a foriegn key of AssociateTypedID and RegionID.
namespace XXX.Models
{
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual ICollection<AssociateType> AssociateTypes { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
}
AND
namespace XXX.Models
{
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class Region
{
public int RegionId { get; set; }
public int RegionName { get; set; }
public int RegionDescription { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
}
AND
namespace XXX.Models
{
public class XXXDb : DbContext
{
public XXXDb(): base("name=DefaultConnection")
{
}
public DbSet<Associate> Associates { get; set; }
public DbSet<AssociateType> AssociateTypes { get; set; }
public DbSet<Region> Regions { get; set; }
}
}
So I have updated my code above and I'm getting very close to where I need to be in my database. I have the following tables generated.
Associates, AssociateTypes & Regions (each of them have the columns I would expect)
BUT I now have a new table called RegionAssociates which has the following columns:
Region_RegionId (int) & Associate_AssociateId (int)
This table was not expected or needed in my schema.
Your classes doesn't match your description of the model. You are saying
Each Associate can have a designation of AssociateType
I suppose that the same AssociateType can be assigned to more Associates, so there should be 1:N relationship between AssociateType and Associate.
But the Associate class defines the relationship the other way around - by convention public virtual ICollection<AssociateType> AssociateType { get; set; } creates 1:N relationship between Associate and AssociateType.
the correct definition of your classes would be
public class Associate
{
public int AssociateId { get; set; }
public string AssociateName { get; set; }
public int AddressNumber { get; set; }
public string AddressStreet { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string MainPhoneNumber { get; set; }
public string AssociateEmail { get; set; }
public string AssociateWebsite { get; set; }
public int RegionId { get; set; }
public int AssociateTypeId { get; set; }
public virtual AssociateType AssociateType { get; set; }
public string ContactFirstName { get; set; }
public string ContactLastName { get; set; }
public string ContactPhoneNumber { get; set; }
public string ContactEmail { get; set; }
public virtual ICollection<Region> Regions { get; set; }
}
public class AssociateType
{
public int AssociateTypeId { get; set; }
public string AssociateTypeName { get; set; }
public virtual ICollection<Associate> Associates { get; set; }
}
Can't say for sure what is missing from your configuration as you did't post it, but if you are using the fluent api something like this should fix the problem:
modelBuilder.Entity<AssociateType>()
.HasKey(t => t.AssociateTypeId);
modelBuilder.Entity<Associate>()
.HasRequired(t => t.AssociateType)
.WithRequiredPrincipal(t => t.Associate);
The above is adapted from this article http://msdn.microsoft.com/en-us/data/jj591620.aspx