-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
- Loading branch information
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
using AutoMapper; | ||
using Vidly.Dtos; | ||
using Vidly.Models; | ||
|
||
namespace Vidly.App_Start | ||
{ | ||
public class MappingProfile : Profile | ||
{ | ||
public MappingProfile() | ||
{ | ||
Mapper.CreateMap<Customer, CustomerDto>(); | ||
Mapper.CreateMap<CustomerDto, Customer>(); | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong. |
||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Web.Http; | ||
using Newtonsoft.Json; | ||
using Newtonsoft.Json.Serialization; | ||
|
||
namespace Vidly | ||
{ | ||
public static class WebApiConfig | ||
{ | ||
public static void Register(HttpConfiguration config) | ||
{ | ||
var settings = config.Formatters.JsonFormatter.SerializerSettings; | ||
settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); | ||
settings.Formatting = Formatting.Indented; | ||
|
||
config.MapHttpAttributeRoutes(); | ||
|
||
config.Routes.MapHttpRoute( | ||
name: "DefaultApi", | ||
routeTemplate: "api/{controller}/{id}", | ||
defaults: new { id = RouteParameter.Optional } | ||
); | ||
} | ||
} | ||
} | ||
This comment has been minimized.
Sorry, something went wrong.
demetrous
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
using AutoMapper; | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Net; | ||
using System.Web.Http; | ||
using Vidly.Dtos; | ||
using Vidly.Models; | ||
|
||
namespace Vidly.Controllers.Api | ||
{ | ||
public class CustomersController : ApiController | ||
{ | ||
private ApplicationDbContext _context; | ||
|
||
public CustomersController() | ||
{ | ||
_context = new ApplicationDbContext(); | ||
} | ||
|
||
// GET /api/customers | ||
public IEnumerable<CustomerDto> GetCustomers() | ||
{ | ||
return _context.Customers.ToList().Select(Mapper.Map<Customer, CustomerDto>); | ||
This comment has been minimized.
Sorry, something went wrong.
jeremyj563
|
||
} | ||
|
||
// GET /api/customers/1 | ||
public IHttpActionResult GetCustomer(int id) | ||
{ | ||
var customer = _context.Customers.SingleOrDefault(c => c.Id == id); | ||
|
||
if (customer == null) | ||
return NotFound(); | ||
|
||
return Ok(Mapper.Map<Customer, CustomerDto>(customer)); | ||
} | ||
|
||
// POST /api/customers | ||
[HttpPost] | ||
public IHttpActionResult CreateCustomer(CustomerDto customerDto) | ||
{ | ||
if (!ModelState.IsValid) | ||
return BadRequest(); | ||
|
||
var customer = Mapper.Map<CustomerDto, Customer>(customerDto); | ||
_context.Customers.Add(customer); | ||
_context.SaveChanges(); | ||
|
||
customerDto.Id = customer.Id; | ||
return Created(new Uri(Request.RequestUri + "/" + customer.Id), customerDto); | ||
} | ||
|
||
This comment has been minimized.
Sorry, something went wrong.
chrisasmith
|
||
// PUT /api/customers/1 | ||
[HttpPut] | ||
public void UpdateCustomer(int id, CustomerDto customerDto) | ||
{ | ||
if (!ModelState.IsValid) | ||
throw new HttpResponseException(HttpStatusCode.BadRequest); | ||
|
||
var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id); | ||
|
||
if (customerInDb == null) | ||
throw new HttpResponseException(HttpStatusCode.NotFound); | ||
|
||
Mapper.Map(customerDto, customerInDb); | ||
|
||
_context.SaveChanges(); | ||
} | ||
|
||
// DELETE /api/customers/1 | ||
[HttpDelete] | ||
public void DeleteCustomer(int id) | ||
{ | ||
var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id); | ||
|
||
if (customerInDb == null) | ||
throw new HttpResponseException(HttpStatusCode.NotFound); | ||
|
||
_context.Customers.Remove(customerInDb); | ||
_context.SaveChanges(); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
using System; | ||
using System.ComponentModel.DataAnnotations; | ||
using Vidly.Models; | ||
|
||
namespace Vidly.Dtos | ||
{ | ||
public class CustomerDto | ||
{ | ||
public int Id { get; set; } | ||
|
||
[Required] | ||
[StringLength(255)] | ||
public string Name { get; set; } | ||
|
||
public bool IsSubscribedToNewsletter { get; set; } | ||
|
||
public byte MembershipTypeId { get; set; } | ||
|
||
// [Min18YearsIfAMember] | ||
public DateTime? Birthdate { get; set; } | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,18 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Web; | ||
using AutoMapper; | ||
using System.Web.Http; | ||
using System.Web.Mvc; | ||
using System.Web.Optimization; | ||
using System.Web.Routing; | ||
using Vidly.App_Start; | ||
|
||
namespace Vidly | ||
{ | ||
public class MvcApplication : System.Web.HttpApplication | ||
{ | ||
protected void Application_Start() | ||
{ | ||
Mapper.Initialize(c => c.AddProfile<MappingProfile>()); | ||
GlobalConfiguration.Configure(WebApiConfig.Register); | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
dennisshen7
|
||
AreaRegistration.RegisterAllAreas(); | ||
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); | ||
RouteConfig.RegisterRoutes(RouteTable.Routes); | ||
|
22 comments
on commit ca3f335
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i don't how the Api controller was Added, and the explanation was not explicit
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry for this question but i've an issue when trying to add an asp.net web api 2 conroller to my project !
Error message is : specified argument was out of range of valid values. Parameter name: supportedFrameworks
In parallel, i'm trying to find solution, i tried to enable Internet Services (ISS) features and restart PC/VS but it didn't work. So if anyone has faced this problem and solved it, it would be nice to share the solution.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@iambashir, the Api controller was shown in lecture 65. He added a folder and right-clicked the folder and selected the "asp.net web api 2" controller.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@abdelgrib, it looks like stackoverflow has a couple of solutions: https://stackoverflow.com/questions/17772216/specified-argument-was-out-of-the-range-of-valid-values-parameter-name-site
Most commonly, it looks like you should "go
•control panel
•Programs
•open or close windows features
•tick internet information services
•then restart your visual studio"
Best of luck.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
public IEnumerable<CustomerDto> GetCustomers()
+ {
+ return _context.Customers.ToList().Select(Mapper.Map<Customer, CustomerDto>);
+ }
everything is working fine except the Id property. After mapping in all the list objects of customers Id property becomes 0 . any solution ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I found that Customer class still influences Dto in custom validation, where in CustomerDto class we have this:
// [Min18YearsIfAMember]
public DateTime? Birthdate { get; set; }
In Customer class custom validation is not commented
[Min18YearsIfAMember]
public DateTime? Birthdate { get; set; }
If Birthdate is not valid, this throws an Exception while trying to insert o update a Customer, is custom validation not supported on API?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi guys.
After I changed my return type to IHttpActionResult, I have been unable to use the api controller methods such as BadRequest, Create, Ok, etc. It just seems like they are not found in any namespace. Were they replaced in newer versions of .net?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lvlessi, did you fix that? Im having that problem now, all of returned customers have ID of 0
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Found the reason, for future students:
If you are getting an Id of 0, check your mappingProfile() to ensure that the opt.Ignore is on the Dto to Domain NOT Domain to Dto:
public MappingProfile()
{
// Domain to Dto
Mapper.CreateMap<Customer, CustomerDto>();
Mapper.CreateMap<Movie, MovieDto>();
// Dto to Domain
Mapper.CreateMap<CustomerDto, Customer>()
.ForMember(c => c.Id, opt => opt.Ignore());
Mapper.CreateMap<MovieDto, Movie>()
.ForMember(c => c.Id, opt => opt.Ignore());
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
+joshmowork . glag you did it yourself ! I solved it in the same way you did
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So did you explain mapper in anther course? Bc this was extremely vague and I have to search a whole different source to find information why and how to use mapper..
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@sjardi I thought it was a pretty convenient feature and the beauty of it is to just know what it does, not how it does it. It automatically maps fields with same name in the course.
You can check this small tutorial:
https://www.c-sharpcorner.com/blogs/using-automapper-in-c-sharp
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Mosh didn't mention that you need to comment out the custom validation [min18years...] in the CustomerDto class.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@amossZorin Weird I remember he did and showed the reason why
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@amossZorin Weird I remember he did and showed the reason why
Ah you're right. He mentions it in the IHttpSctionResult video. I was testing it immediately after the Auto Mapper video before.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For those that are receiving 404 errors on their PUT and DELETE calls, add the following code to your Web.config file:
<validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers>
This enables those calls. For security reasons they are disabled by default.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried to install and work with automapper 10.0.0. Seems like some functions were showing deprecated. So i did it in the following way
- In MappingProfile constructor instead of Mapper.CreateMap<...> we just have to use CreateMap<...>
public class MappingProfile : Profile { public MappingProfile() { CreateMap<Customer, CustomerDto>(); CreateMap<CustomerDto, Customer>(); } }
- create another class AutoMapperConfiguration.cs and inside code:
` public class AutoMapperConfiguration
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration( c =>
{
c.AddProfile<MappingProfile>();
});
return config;
}
}`
-
Nothing to do in Global.asax.cs
-
Now in CustomerController.cs:
` public class CustomersController : ApiController
{private ApplicationDbContext _context; private MapperConfiguration config; private IMapper iMapper; public CustomersController() { _context = new ApplicationDbContext(); config = new AutoMapperConfiguration().Configure(); iMapper = config.CreateMapper(); } // GET /api/customers public IEnumerable<CustomerDto> GetCustomers() { // return _context.Customers.ToList(); return _context.Customers.ToList().Select(iMapper.Map<Customer, CustomerDto>); }`
-
wish this helps someone. It works for me but if anyone thinks its not the proper way then please let me know.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tôi đã cố gắng cài đặt và làm việc với automapper 10.0.0. Có vẻ như một số hàm hiển thị không được dùng nữa. Vì vậy, tôi đã làm theo cách sau
- Trong phương thức khởi tạo MappingProfile thay vì Mapper.CreateMap <...> chúng ta chỉ cần sử dụng CreateMap <...>
public class MappingProfile : Profile { public MappingProfile() { CreateMap<Customer, CustomerDto>(); CreateMap<CustomerDto, Customer>(); } }
- tạo một lớp khác AutoMapperConfiguration.cs và mã bên trong:
`public class AutoMapperConfiguration
{public MapperConfiguration Configure() { var config = new MapperConfiguration( c => { c.AddProfile<MappingProfile>(); }); return config; } }`
- Không có gì để làm trong Global.asax.cs
- Bây giờ trong CustomerController.cs:
`public class HotelsController: ApiController
{private ApplicationDbContext _context; private MapperConfiguration config; private IMapper iMapper; public CustomersController() { _context = new ApplicationDbContext(); config = new AutoMapperConfiguration().Configure(); iMapper = config.CreateMapper(); } // GET /api/customers public IEnumerable<CustomerDto> GetCustomers() { // return _context.Customers.ToList(); return _context.Customers.ToList().Select(iMapper.Map<Customer, CustomerDto>); }`
- ước gì điều này giúp ích cho ai đó. Nó làm việc cho tôi nhưng nếu có ai nghĩ rằng nó không phải là cách thích hợp thì vui lòng cho tôi biết.
Respect <3
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Id is auto-generated, you do not need to pass it