Skip to content

Commit

Permalink
Build an API for customers.
Browse files Browse the repository at this point in the history
  • Loading branch information
mosh-hamedani committed Apr 16, 2016
1 parent e5b9945 commit ca3f335
Show file tree
Hide file tree
Showing 8 changed files with 189 additions and 13 deletions.
15 changes: 15 additions & 0 deletions Vidly/App_Start/MappingProfile.cs
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.

Copy link
@sin2akshay

sin2akshay Apr 7, 2019

Id is auto-generated, you do not need to pass it

This comment has been minimized.

Copy link
@shubhamshkl

shubhamshkl Jul 22, 2021

how to use it for latest version of automapper

}
}
}
27 changes: 27 additions & 0 deletions Vidly/App_Start/WebApiConfig.cs
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.

Copy link
@demetrous

demetrous Dec 11, 2018

This file hasn't been generated automatically so I had to add it manually then the app has started to work again

This comment has been minimized.

Copy link
@Imbaker1234

Imbaker1234 Aug 31, 2019

Yeah. Spent quite a bit messing with this before coming here to check.

This comment has been minimized.

Copy link
@pphuppertz

pphuppertz Oct 16, 2020

We were told to create it in the course, folks.

83 changes: 83 additions & 0 deletions Vidly/Controllers/Api/CustomersController.cs
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.

Copy link
@jeremyj563

jeremyj563 Aug 16, 2018

For anyone rewriting this in VB.NET. This line can be rewritten as:

Return _context.Customers.ToList().[Select](AddressOf Mapper.Map(Of Customer, CustomerDto))

}

// 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.

Copy link
@chrisasmith

chrisasmith Nov 10, 2017

To the the CreateCustomer to work I had to add the lines below to "web.config".
Code would not stop crashing when creating a new customer.

Any reason why I had to do this? (I am using Win VS 2017)

This comment has been minimized.

Copy link
@sarmad99

sarmad99 Jan 4, 2019

To the the CreateCustomer to work I had to add the lines below to "web.config".
Code would not stop crashing when creating a new customer.

Any reason why I had to do this? (I am using Win VS 2017)

what lines below are you talking about

This comment has been minimized.

Copy link
@micaelatucker26

micaelatucker26 May 19, 2019

In Visual Studio 2017, I don't have a file called web.config that is generated automatically. Should I create that file by myself? I'm using ASP.NET Core so I wonder what web.config changes to in Core?

This comment has been minimized.

Copy link
@keeponjammin

keeponjammin Jul 29, 2019

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.

This comment has been minimized.

Copy link
@TemplarEnergy

TemplarEnergy Mar 23, 2020

I can't seem to get package manager to load AutoMapper version 4.1. It come back with what I assume to be an incompatibility of versions. Any suggestions. I'm running VS2019.


Attempting to gather dependency information for package 'automapper.4.1.0' with respect to project 'Vidly', targeting '.NETFramework,Version=v4.7.2'
install-package : An error occurred while retrieving package metadata for
'automapper.4.1.0' from source 'Syncfusion_UWP'.
Failed to fetch results from V2 feed at 'https://nuget.syncfusion.com/nuget_universa
lwindows/nuget/getsyncfusionpackages/universalwindows/Packages(Id='automapper',Version
='4.1.0')' with following message : Response status code does not indicate success:
500 (Internal Server Error).
Response status code does not indicate success: 500 (Internal Server Error).
At line:1 char:1

  • install-package automapper -version:4.1
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.P 
     owerShellCmdlets.InstallPackageCommand
    
    

Time Elapsed: 00:00:00.7595051

This comment has been minimized.

Copy link
@Thamin96

Thamin96 Apr 9, 2020

{
"message": "An error has occurred.",
"exceptionMessage": "Value cannot be null.\r\nParameter name: entity",
"exceptionType": "System.ArgumentNullException",
"stackTrace": " at System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName)\r\n at System.Data.Entity.DbSet1.Add(TEntity entity)\r\n at Vidly.Controllers.Api.CustomersController.CreateCustomer(CustomerDto customerDto) in c:\\Users\\Aditya Dev\\Desktop\\Project\\Vidly\\Vidly\\Controllers\\Api\\CustomersController.cs:line 43\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
}
can any one tell me why i am getting these error

This comment has been minimized.

Copy link
@Phantom2017

Phantom2017 Jun 22, 2020

You have to add this attribute beside the argument of CreateCustomer:
public IHttpActionResult CreateCustomer(**[FromBody]**CustomerDto customerDto)

// 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();
}
}
}
22 changes: 22 additions & 0 deletions Vidly/Dtos/CustomerDto.cs
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; }
}
}
9 changes: 5 additions & 4 deletions Vidly/Global.asax.cs
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.

Copy link
@bobbanovski

bobbanovski Mar 18, 2017

make sure this is before the last three entries or your Apis will not work

This comment has been minimized.

Copy link
@dennisshen7

dennisshen7 Apr 15, 2018

Just leave a note for people who change the "API" folder name in the project: you'll have to modify the routing rule in WebApiConfig.cs or those API would not work correctly.

This comment has been minimized.

Copy link
@micaelatucker26

micaelatucker26 May 19, 2019

I'm using Visual Studio 2017 with Asp.Net Core and I don't have a file called Global.asax . Where can I put the code to initialize Mapper since I am using a newer version?

This comment has been minimized.

Copy link
@y-yildirim

y-yildirim Oct 10, 2019

how can I do the same thing with automapper 9.0?

This comment has been minimized.

Copy link
@KiranSankar

KiranSankar Dec 1, 2019

I'm using Visual Studio 2017 with Asp.Net Core and I don't have a file called Global.asax . Where can I put the code to initialize Mapper since I am using a newer version?

i heard things in global.asax file in mvc should be added in startup.cs in .net core.

This comment has been minimized.

Copy link
@ithas2bee

ithas2bee Sep 20, 2023

If anyone is getting a red underline problem when adding "using System.Web.Http;" and "GlobalConfiguration.Configure(WebApiConfig.Register);" you can potentially fix this by adding the correct NuGet Packages.

In Visual Studio, right-click on your project in the Solution Explorer, select "Manage NuGet Packages," and ensure you have the Microsoft.AspNet.WebApi package installed. If it's not installed, you can search for it in the NuGet Package Manager and install it.

AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
Expand Down
19 changes: 19 additions & 0 deletions Vidly/Vidly.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,31 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="AutoMapper">
<HintPath>..\packages\AutoMapper.4.1.0\lib\net45\AutoMapper.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.2\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Web.Http, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.2\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.2\lib\net45\System.Web.Http.WebHost.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
Expand Down Expand Up @@ -156,13 +171,17 @@
<Compile Include="App_Start\BundleConfig.cs" />
<Compile Include="App_Start\FilterConfig.cs" />
<Compile Include="App_Start\IdentityConfig.cs" />
<Compile Include="App_Start\MappingProfile.cs" />
<Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="App_Start\Startup.Auth.cs" />
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\Api\CustomersController.cs" />
<Compile Include="Controllers\CustomersController.cs" />
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Controllers\ManageController.cs" />
<Compile Include="Controllers\MoviesController.cs" />
<Compile Include="Dtos\CustomerDto.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
Expand Down
22 changes: 13 additions & 9 deletions Vidly/Web.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
Expand All @@ -9,8 +9,7 @@
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Vidly-20160330105730.mdf;Initial Catalog=aspnet-Vidly-20160330105730;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Vidly-20160330105730.mdf;Initial Catalog=aspnet-Vidly-20160330105730;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
Expand All @@ -27,24 +26,29 @@
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
Expand All @@ -68,7 +72,7 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Expand Down
5 changes: 5 additions & 0 deletions Vidly/packages.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Antlr" version="3.4.1.9004" targetFramework="net45" />
<package id="AutoMapper" version="4.1.0" targetFramework="net45" />
<package id="bootstrap" version="3.0.0" targetFramework="net45" />
<package id="EntityFramework" version="6.1.1" targetFramework="net45" />
<package id="jQuery" version="1.10.2" targetFramework="net45" />
Expand All @@ -11,6 +12,10 @@
<package id="Microsoft.AspNet.Mvc" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="3.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="3.2.2" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.2" targetFramework="net45" />
<package id="Microsoft.Owin" version="3.0.0" targetFramework="net45" />
Expand Down

22 comments on commit ca3f335

@amodubashir
Copy link

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

@abdelgrib
Copy link

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.

@KhalidGit
Copy link

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.

@KhalidGit
Copy link

@KhalidGit KhalidGit commented on ca3f335 Jun 21, 2017

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.

@lvlessi
Copy link

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 ?

@AlekRazo
Copy link

@AlekRazo AlekRazo commented on ca3f335 Jul 10, 2017

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?

@rperrino
Copy link

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?

@joshmowork
Copy link

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

@joshmowork
Copy link

@joshmowork joshmowork commented on ca3f335 Aug 28, 2017

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());
}

@lvlessi
Copy link

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

@sjardi
Copy link

@sjardi sjardi commented on ca3f335 Feb 17, 2019

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..

@sin2akshay
Copy link

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

@amossZorin
Copy link

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.

@sin2akshay
Copy link

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

@amossZorin
Copy link

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.

@keeponjammin
Copy link

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.

@Thamin96
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can anyone help me why I got this error and how to solve
Screenshot (23)
Screenshot (24)

@Andres2295
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does anyone know anything about this?

image

I can't seem to find the error. I don't have any red flags in the code. It should be a logical error.

this is a screenshot to my code:

image

@Rashedul007
Copy link

@Rashedul007 Rashedul007 commented on ca3f335 Jul 27, 2020

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.

@PrateekAnand
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can anyone help me why I got this error and how to solve
Screenshot (23)
Screenshot (24)

I am also facing the same problems. Can anyone please help solve this problem.

@truong2307
Copy link

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

@ozcanguler
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does anyone know anything about this?

image

I can't seem to find the error. I don't have any red flags in the code. It should be a logical error.

this is a screenshot to my code:

image

I had the same problem. Add this code to global.asax
api

Please sign in to comment.