37

Here is my controller:

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Milos_MovieStore.DAL; using Milos_MovieStore.Models; using Milos_MovieStore.DTO; using System.Data.Entity; namespace Milos_MovieStore.Controllers.Api { public class CustomersController : ApiController { private DBContext_MovieStore _dbcontext; public CustomersController() { _dbcontext = new DBContext_MovieStore(); } protected override void Dispose(bool disposing) { _dbcontext.Dispose(); } // GET /api/customers [HttpGet] public IHttpActionResult GetCustomers() { List<Customer> customers = _dbcontext.Customers.Include(c => c.MembershipType).ToList(); return Ok(CustomersToDTOList(customers)); } // GET /api/customers/1 [HttpGet] public IHttpActionResult GetCustomer(int id) { Customer customer = _dbcontext.Customers.Include(c => c.MembershipType).SingleOrDefault(c => c.Id == id); if (customer == null) return NotFound(); return Ok(CustomerToDTO(customer)); } //POST /api/customers [HttpPost] public IHttpActionResult CreateCustomer(CustomerDTO customerDTO) { if (!ModelState.IsValid) return BadRequest(); _dbcontext.Customers.Add(DTOToCustomer(customerDTO)); _dbcontext.SaveChanges(); return Created(new Uri(Request.RequestUri + "/" + customerDTO.Id), customerDTO); } // PUT /api/customer/1 [HttpPut] public IHttpActionResult UpdateCustomer(CustomerDTO customerDTO) { if (!ModelState.IsValid) return BadRequest(); Customer customerInDB = _dbcontext.Customers.SingleOrDefault(c => c.Id == customerDTO.Id); if (customerInDB == null) return NotFound(); MapDTOToCustomer(customerDTO, customerInDB); _dbcontext.SaveChanges(); return Ok(customerDTO); } // DELETE /api/customer/1 [HttpDelete] public IHttpActionResult DeleteCustomer(int id) { if (!ModelState.IsValid) return BadRequest(); Customer customerInDB = _dbcontext.Customers.SingleOrDefault(c => c.Id == id); if (customerInDB == null) return NotFound(); _dbcontext.Customers.Remove(customerInDB); _dbcontext.SaveChanges(); return Ok(id); } private CustomerDTO CustomerToDTO(Customer customer) { CustomerDTO customerDTO = new CustomerDTO(); customerDTO.Id = customer.Id; customerDTO.Name = customer.Name; customerDTO.DOB = customer.DOB; customerDTO.MembershipTypeId = customer.MembershipTypeId; customerDTO.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter; return customerDTO; } private Customer DTOToCustomer(CustomerDTO customerDTO) { Customer customer = new Customer(); customer.Id = customerDTO.Id; customer.Name = customerDTO.Name; customer.DOB = customerDTO.DOB; customer.MembershipTypeId = customerDTO.MembershipTypeId; customer.IsSubscribedToNewsletter = customerDTO.IsSubscribedToNewsletter; return customer; } private void MapDTOToCustomer(CustomerDTO customerDTO, Customer customer) { customer.Id = customerDTO.Id; customer.Name = customerDTO.Name; customer.DOB = customerDTO.DOB; customer.MembershipTypeId = customerDTO.MembershipTypeId; customer.IsSubscribedToNewsletter = customerDTO.IsSubscribedToNewsletter; } private IEnumerable<CustomerDTO> CustomersToDTOList(IEnumerable<Customer> customers) { List<CustomerDTO> customersDTO = new List<CustomerDTO>(); foreach (Customer c in customers) { customersDTO.Add(CustomerToDTO(c)); } return customersDTO; } } } 

My DTO:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace Milos_MovieStore.DTO { public class CustomerDTO { public int Id { get; set; } [Required] [StringLength(255)] public string Name { get; set; } public DateTime? DOB { get; set; } public byte MembershipTypeId { get; set; } public bool IsSubscribedToNewsletter { get; set; } } } 

My POST request:

Postman POST request

As you can see in the screenshot, I'm sending DTO in JSON to POST method in API controller. I just can't find a solution. DELETE and GET requests are working with no problem. It is a training project so don't worry about those weird temporary mapping methods I have put in controller.

2
  • What is return Created(new Uri(Request.RequestUri + "/" + customerDTO.Id), customerDTO); ? What is Created() method? Commented Nov 28, 2017 at 3:41
  • ... It's a virtual method in System.Web.Http for creating 201 "created" http response instead of 200 OK. Uri in argument returns string f.e.:"/api/customers" ... Commented Nov 28, 2017 at 4:26

2 Answers 2

75

I found a solution to this.

After I started building, there was build warnings going to the output window but not showing in the main error / warning window.

Check your output/error window if there are errors or warning then try to solve it.

They were to do with assembly conflicts and said recommend putting the assembly redirect in the web.Config.

Once I had went through them all, it now works.

For example:

 <dependentAssembly> <assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" /> <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" /> </dependentAssembly> 

other thing you can try is: make your method like

public IHttpActionResult CreateCustomer([FromBody]CustomerDTO customerDTO){} 

see if this helps.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. Adding your extra code into web.config helped. Now I have to find out why :) . Exception messages in output window was: Exception thrown: 'System.MissingMethodException' in System.Web.Http.dll Exception thrown: 'System.MissingMethodException' in mscorlib.dll Exception thrown: 'System.MissingMethodException' in mscorlib.dll Exception thrown: 'System.MissingMethodException' in mscorlib.dll
+Saurabh Solanki ... yes, thanks. I have added your script into web.config and it works. May I ask you what was the actual problem ? ...
i think you have forgot to add assembly reference, so after adding script to web config it starts working. if you found my answer helpful then you can mark it as accepted answer.. so other who visit your question they may got this answer worked for you or not..
This worked for me-- thank you!-- and I will note that after the individual warnings, there was a final line that included the entire XML set to be added to the web.config. I copy-pasted that chunk into the <runtime> section of the config and it cleared everything up.
In my case, the entry already existed in the web.config, but the newest version in the range as well as the newVersion parameter capped out at 2.0.0.0. Updating it to 4.2.0.0 fixed things.
|
8

I have the same problem but from a different side. I have the MyProject with System.Net.Http library and MyUnitTestProject with System.Net.Http too. Once upon a time then I started Unit Tests it crashed with a strange problem. Inconclusive: test not run: Inconclusive: test not run

And where was some exception "JetBrains exited with code ...." which says nothing for me: ReSharper Unit Test exception

Then I figured out what the problem was in the binding redirect for System.Net.Http which was added by some NuGet package. I remove the binding redirect, but gain another exception, close to yours "System.Net.Http.HttpRequestMessage...”: enter image description here

The problem was in versions of libraries - in MyProject was 4.0.0.0 (from .net Framework), but MyUnitTestProject was 4.2.0.0 (from Visual Studio folder), and the binding redirect was added for 4.2.0.0 which I think somehow cant be found. So I change it to 4.0.0.0 and it worked:

<dependentAssembly> <assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" /> <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" /> </dependentAssembly> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.