├── .gitattributes ├── .gitignore ├── CRUDOperationUsingWEBAPI.csproj ├── CRUDOperationUsingWEBAPI.sln ├── Context └── StudentDBContext.cs ├── Controllers ├── StudentsController.cs ├── UsersController.cs └── WeatherForecastController.cs ├── Data ├── Student.cs └── Users.cs ├── Images └── test.png ├── Migrations ├── 20220702105428_mg1.Designer.cs ├── 20220702105428_mg1.cs ├── 20220702110219_mg2.Designer.cs ├── 20220702110219_mg2.cs ├── 20220703131158_adding_identity.Designer.cs ├── 20220703131158_adding_identity.cs ├── 20220724133121_mp-3.Designer.cs ├── 20220724133121_mp-3.cs └── StudentDBContextModelSnapshot.cs ├── Models ├── AssignRoleToUserDTO.cs ├── AuthenticateUser.cs ├── AuthenticationResponse.cs ├── CreateRoleDTO.cs ├── DeleteStudentDTO.cs ├── DeleteUserDTO.cs ├── ErrorResponse.cs ├── MainResponse.cs ├── RefreshTokenRequest.cs ├── RegisterUserDTO.cs ├── StudentDTO.cs └── UpdateStudentDTO.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Services ├── IStudentService.cs └── StudentService.cs ├── WeatherForecast.cs ├── appsettings.Development.json └── appsettings.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /CRUDOperationUsingWEBAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /CRUDOperationUsingWEBAPI.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32616.157 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CRUDOperationUsingWEBAPI", "CRUDOperationUsingWEBAPI.csproj", "{4CEB6CAF-3BEE-426F-B72C-3E44817931D6}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {4CEB6CAF-3BEE-426F-B72C-3E44817931D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {4CEB6CAF-3BEE-426F-B72C-3E44817931D6}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {4CEB6CAF-3BEE-426F-B72C-3E44817931D6}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {4CEB6CAF-3BEE-426F-B72C-3E44817931D6}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {E2A8FCF5-E7CD-4F84-97C4-A24431C3D34F} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Context/StudentDBContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using CRUDOperationUsingWEBAPI.Data; 6 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 7 | using Microsoft.AspNetCore.Identity; 8 | 9 | namespace CRUDOperationUsingWEBAPI.Context 10 | { 11 | public partial class StudentDBContext : IdentityDbContext 12 | { 13 | 14 | public StudentDBContext(DbContextOptions options) 15 | : base(options) 16 | { 17 | } 18 | 19 | public DbSet Students { get; set; } 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | base.OnModelCreating(modelBuilder); 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Controllers/StudentsController.cs: -------------------------------------------------------------------------------- 1 | using CRUDOperationUsingWEBAPI.Models; 2 | using CRUDOperationUsingWEBAPI.Services; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace CRUDOperationUsingWEBAPI.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [Authorize] 10 | [ApiController] 11 | public class StudentsController : ControllerBase 12 | { 13 | private readonly IStudentService _studentService; 14 | 15 | public StudentsController(IStudentService studentService) 16 | { 17 | _studentService = studentService; 18 | } 19 | 20 | [HttpGet("GetAllStudent")] 21 | public async Task GetAllStudent() 22 | { 23 | try 24 | { 25 | var response = await _studentService.GetAllStudent(); 26 | return Ok(response); 27 | } 28 | catch (Exception ex) 29 | { 30 | return ErrorResponse.ReturnErrorResponse(ex.Message); 31 | } 32 | } 33 | 34 | [HttpGet("GetStudentByStudentID/{StudentID}")] 35 | public async Task GetStudentByStudentID(int StudentID) 36 | { 37 | try 38 | { 39 | var response = await _studentService.GetStudentByStudentID(StudentID); 40 | return Ok(response); 41 | } 42 | catch (Exception ex) 43 | { 44 | return ErrorResponse.ReturnErrorResponse(ex.Message); 45 | } 46 | } 47 | 48 | 49 | [HttpPost("AddStudent")] 50 | public async Task AddStudent([FromBody] StudentDTO studentInfo) 51 | { 52 | try 53 | { 54 | var response = await _studentService.AddStudent(studentInfo); 55 | return Ok(response); 56 | } 57 | catch (Exception ex) 58 | { 59 | return ErrorResponse.ReturnErrorResponse(ex.Message); 60 | } 61 | 62 | } 63 | 64 | [HttpPut("UpdateStudent")] 65 | public async Task UpdateStudent([FromBody] UpdateStudentDTO studentInfo) 66 | { 67 | try 68 | { 69 | var response = await _studentService.UpdateStudent(studentInfo); 70 | return Ok(response); 71 | } 72 | catch (Exception ex) 73 | { 74 | return ErrorResponse.ReturnErrorResponse(ex.Message); 75 | } 76 | 77 | } 78 | 79 | [HttpDelete("DeleteStudent")] 80 | public async Task DeleteStudent([FromBody] DeleteStudentDTO studentInfo) 81 | { 82 | try 83 | { 84 | var response = await _studentService.DeleteStudent(studentInfo); 85 | return Ok(response); 86 | 87 | } 88 | catch (Exception ex) 89 | { 90 | return ErrorResponse.ReturnErrorResponse(ex.Message); 91 | } 92 | 93 | } 94 | 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using CRUDOperationUsingWEBAPI.Data; 2 | using CRUDOperationUsingWEBAPI.Models; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Http; 5 | using Microsoft.AspNetCore.Identity; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.IdentityModel.Tokens; 8 | using System.IdentityModel.Tokens.Jwt; 9 | using System.Security.Claims; 10 | using System.Security.Cryptography; 11 | using System.Text; 12 | 13 | namespace CRUDOperationUsingWEBAPI.Controllers 14 | { 15 | [Route("api/[controller]")] 16 | [Authorize] 17 | [ApiController] 18 | public class UsersController : ControllerBase 19 | { 20 | private readonly UserManager _userManager; 21 | private readonly RoleManager _roleManager; 22 | private readonly IConfiguration _configuration; 23 | private readonly IWebHostEnvironment _webHostEnvironment; 24 | public UsersController(UserManager userManager, 25 | IConfiguration configuration, RoleManager roleManager, IWebHostEnvironment webHostEnvironment) 26 | { 27 | _userManager = userManager; 28 | _roleManager = roleManager; 29 | _configuration = configuration; 30 | _webHostEnvironment = webHostEnvironment; 31 | } 32 | 33 | 34 | [HttpPost("CreateRole")] 35 | public async Task CreateRole(CreateRoleDTO roleDTO) 36 | { 37 | 38 | var response = await _roleManager.CreateAsync(new IdentityRole 39 | { 40 | Name = roleDTO.RoleName 41 | }); 42 | 43 | if (response.Succeeded) 44 | { 45 | return Ok("New Role Created"); 46 | } 47 | else 48 | { 49 | return BadRequest(response.Errors); 50 | } 51 | } 52 | 53 | 54 | [HttpPost("AssignRoleToUser")] 55 | public async Task AssignRoleToUser(AssignRoleToUserDTO assignRoleToUserDTO) 56 | { 57 | 58 | var userDetails = await _userManager.FindByEmailAsync(assignRoleToUserDTO.Email); 59 | 60 | if (userDetails != null) 61 | { 62 | 63 | var userRoleAssignResponse = await _userManager.AddToRoleAsync(userDetails, assignRoleToUserDTO.RoleName); 64 | 65 | if (userRoleAssignResponse.Succeeded) 66 | { 67 | return Ok("Role Assigned to User: " + assignRoleToUserDTO.RoleName); 68 | } 69 | else 70 | { 71 | return BadRequest(userRoleAssignResponse.Errors); 72 | } 73 | } 74 | else 75 | { 76 | return BadRequest("There are no user exist with this email"); 77 | } 78 | 79 | 80 | } 81 | 82 | [AllowAnonymous] 83 | [HttpPost("RefreshToken")] 84 | public async Task RefreshToken(RefreshTokenRequest refreshTokenRequest) 85 | { 86 | var response = new MainResponse(); 87 | if (refreshTokenRequest is null) 88 | { 89 | response.ErrorMessage = "Invalid request"; 90 | return BadRequest(response); 91 | } 92 | 93 | var principal = GetPrincipalFromExpiredToken(refreshTokenRequest.AccessToken); 94 | 95 | if (principal != null) 96 | { 97 | var email = principal.Claims.FirstOrDefault(f => f.Type == ClaimTypes.Email); 98 | 99 | var user = await _userManager.FindByEmailAsync(email?.Value); 100 | 101 | if (user is null || user.RefreshToken != refreshTokenRequest.RefreshToken) 102 | { 103 | response.ErrorMessage = "Invalid Request"; 104 | return BadRequest(response); 105 | } 106 | 107 | string newAccessToken = GenerateAccessToken(user); 108 | string refreshToken = GenerateRefreshToken(); 109 | 110 | user.RefreshToken = refreshToken; 111 | await _userManager.UpdateAsync(user); 112 | 113 | response.IsSuccess = true; 114 | response.Content = new AuthenticationResponse 115 | { 116 | RefreshToken = refreshToken, 117 | AccessToken = newAccessToken 118 | }; 119 | return Ok(response); 120 | } 121 | else 122 | { 123 | return ErrorResponse.ReturnErrorResponse("Invalid Token Found"); 124 | } 125 | 126 | } 127 | 128 | 129 | 130 | [AllowAnonymous] 131 | [HttpPost("AuthenticateUser")] 132 | public async Task AuthenticateUser(AuthenticateUser authenticateUser) 133 | { 134 | var user = await _userManager.FindByNameAsync(authenticateUser.UserName); 135 | if (user == null) return Unauthorized(); 136 | 137 | bool isValidUser = await _userManager.CheckPasswordAsync(user, authenticateUser.Password); 138 | 139 | if (isValidUser) 140 | { 141 | string accessToken = GenerateAccessToken(user); 142 | var refreshToken = GenerateRefreshToken(); 143 | user.RefreshToken = refreshToken; 144 | await _userManager.UpdateAsync(user); 145 | 146 | var response = new MainResponse 147 | { 148 | Content = new AuthenticationResponse 149 | { 150 | RefreshToken = refreshToken, 151 | AccessToken = accessToken 152 | }, 153 | IsSuccess = true, 154 | ErrorMessage = "" 155 | }; 156 | return Ok(response); 157 | } 158 | else 159 | { 160 | return Unauthorized(); 161 | } 162 | 163 | } 164 | 165 | private string GenerateAccessToken(Users user) 166 | { 167 | var tokenHandler = new JwtSecurityTokenHandler(); 168 | 169 | var keyDetail = Encoding.UTF8.GetBytes(_configuration["JWT:Key"]); 170 | 171 | var claims = new List 172 | { 173 | new Claim(ClaimTypes.NameIdentifier, user.Id), 174 | new Claim(ClaimTypes.Name, $"{user.FirstName} { user.LastName}"), 175 | new Claim(ClaimTypes.Email, user.Email), 176 | new Claim("UserAvatar", $"{user.UserAvatar}"), 177 | 178 | }; 179 | 180 | var tokenDescriptor = new SecurityTokenDescriptor 181 | { 182 | Audience = _configuration["JWT:Audience"], 183 | Issuer = _configuration["JWT:Issuer"], 184 | Expires = DateTime.UtcNow.AddMinutes(30), 185 | Subject = new ClaimsIdentity(claims), 186 | SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyDetail), SecurityAlgorithms.HmacSha256Signature) 187 | }; 188 | var token = tokenHandler.CreateToken(tokenDescriptor); 189 | return tokenHandler.WriteToken(token); 190 | } 191 | private ClaimsPrincipal GetPrincipalFromExpiredToken(string token) 192 | { 193 | var tokenHandler = new JwtSecurityTokenHandler(); 194 | 195 | var keyDetail = Encoding.UTF8.GetBytes(_configuration["JWT:Key"]); 196 | var tokenValidationParameter = new TokenValidationParameters 197 | { 198 | ValidateIssuer = false, 199 | ValidateAudience = false, 200 | ValidateLifetime = false, 201 | ValidateIssuerSigningKey = true, 202 | ValidIssuer = _configuration["JWT:Issuer"], 203 | ValidAudience = _configuration["JWT:Audience"], 204 | IssuerSigningKey = new SymmetricSecurityKey(keyDetail), 205 | }; 206 | 207 | SecurityToken securityToken; 208 | var principal = tokenHandler.ValidateToken(token, tokenValidationParameter, out securityToken); 209 | var jwtSecurityToken = securityToken as JwtSecurityToken; 210 | if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) 211 | throw new SecurityTokenException("Invalid token"); 212 | return principal; 213 | } 214 | 215 | private string GenerateRefreshToken() 216 | { 217 | 218 | var randomNumber = new byte[32]; 219 | using (var rng = RandomNumberGenerator.Create()) 220 | { 221 | rng.GetBytes(randomNumber); 222 | return Convert.ToBase64String(randomNumber); 223 | } 224 | } 225 | 226 | [AllowAnonymous] 227 | [HttpPost("RegisterUser")] 228 | public async Task RegisterUser(RegisterUserDTO registerUserDTO) 229 | { 230 | 231 | var userToBeCreated = new Users 232 | { 233 | Email = registerUserDTO.Email, 234 | FirstName = registerUserDTO.FirstName, 235 | LastName = registerUserDTO.LastName, 236 | UserName = registerUserDTO.Email, 237 | Address = registerUserDTO.Address, 238 | Gender = registerUserDTO.Gender 239 | }; 240 | 241 | 242 | if (!string.IsNullOrWhiteSpace(registerUserDTO.UserAvatar)) 243 | { 244 | byte[] imgBytes = Convert.FromBase64String(registerUserDTO.UserAvatar); 245 | string fileName = $"{Guid.NewGuid()}_{userToBeCreated.FirstName.Trim()}_{userToBeCreated.LastName.Trim()}.jpeg"; 246 | string avatar = await UploadFile(imgBytes, fileName); 247 | userToBeCreated.UserAvatar = avatar; 248 | } 249 | 250 | var response = await _userManager.CreateAsync(userToBeCreated, registerUserDTO.Password); 251 | if (response.Succeeded) 252 | { 253 | return Ok(new MainResponse 254 | { 255 | IsSuccess = true, 256 | }); 257 | } 258 | else 259 | { 260 | return ErrorResponse.ReturnErrorResponse(response.Errors?.ToString() ?? ""); 261 | } 262 | } 263 | 264 | private async Task UploadFile(byte[] bytes, string fileName) 265 | { 266 | string uploadsFolder = Path.Combine("Images", fileName); 267 | Stream stream = new MemoryStream(bytes); 268 | using (var ms = new FileStream(uploadsFolder, FileMode.Create)) 269 | { 270 | await stream.CopyToAsync(ms); 271 | } 272 | return uploadsFolder; 273 | } 274 | 275 | [HttpDelete("DeleteUser")] 276 | public async Task DeleteUser(DeleteUserDTO userDetails) 277 | { 278 | 279 | var existingUser = await _userManager.FindByEmailAsync(userDetails.Email); 280 | if (existingUser != null) 281 | { 282 | var response = await _userManager.DeleteAsync(existingUser); 283 | 284 | if (response.Succeeded) 285 | { 286 | return Ok(new MainResponse 287 | { 288 | IsSuccess = true, 289 | }); 290 | } 291 | else 292 | { 293 | return ErrorResponse.ReturnErrorResponse(response.Errors?.ToString() ?? ""); 294 | } 295 | } 296 | else 297 | { 298 | return ErrorResponse.ReturnErrorResponse("No User found with this email"); 299 | } 300 | } 301 | } 302 | } 303 | -------------------------------------------------------------------------------- /Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace CRUDOperationUsingWEBAPI.Controllers 4 | { 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | 16 | public WeatherForecastController(ILogger logger) 17 | { 18 | _logger = logger; 19 | } 20 | 21 | [HttpGet(Name = "GetWeatherForecast")] 22 | public IEnumerable Get() 23 | { 24 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 25 | { 26 | Date = DateTime.Now.AddDays(index), 27 | TemperatureC = Random.Shared.Next(-20, 55), 28 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 29 | }) 30 | .ToArray(); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Data/Student.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace CRUDOperationUsingWEBAPI.Data 4 | { 5 | public class Student 6 | { 7 | [Key] 8 | public int StudentID { get; set; } 9 | [MaxLength(50)] 10 | public string FirstName { get; set; } = null!; 11 | 12 | [MaxLength(50)] 13 | public string LastName { get; set; } = null!; 14 | [MaxLength(50)] 15 | public string Email { get; set; } = null!; 16 | 17 | [MaxLength(10)] 18 | public string Gender { get; set; } = null!; 19 | public string? Address { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Data/Users.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace CRUDOperationUsingWEBAPI.Data 5 | { 6 | public class Users : IdentityUser 7 | { 8 | [MaxLength(50)] 9 | public string FirstName { get; set; } = null!; 10 | 11 | [MaxLength(50)] 12 | public string LastName { get; set; } = null!; 13 | 14 | 15 | [MaxLength(6)] 16 | public string Gender { get; set; } = null!; 17 | public string? Address { get; set; } 18 | public string? RefreshToken { get; set; } 19 | public string? UserAvatar { get; set; } 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Images/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mistrypragnesh40/CreatingWebAPIDemo/19a4834590bfac0055a48c9ed7f5ecd97e522cc6/Images/test.png -------------------------------------------------------------------------------- /Migrations/20220702105428_mg1.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CRUDOperationUsingWEBAPI.Context; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace CRUDOperationUsingWEBAPI.Migrations 12 | { 13 | [DbContext(typeof(StudentDBContext))] 14 | [Migration("20220702105428_mg1")] 15 | partial class mg1 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("ProductVersion", "6.0.6") 22 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 23 | 24 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 25 | 26 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Student", b => 27 | { 28 | b.Property("StudentID") 29 | .ValueGeneratedOnAdd() 30 | .HasColumnType("int"); 31 | 32 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StudentID"), 1L, 1); 33 | 34 | b.Property("Address") 35 | .HasColumnType("nvarchar(max)"); 36 | 37 | b.Property("Email") 38 | .IsRequired() 39 | .HasColumnType("nvarchar(max)"); 40 | 41 | b.Property("FirstName") 42 | .IsRequired() 43 | .HasColumnType("nvarchar(max)"); 44 | 45 | b.Property("Gender") 46 | .IsRequired() 47 | .HasColumnType("nvarchar(max)"); 48 | 49 | b.Property("LastName") 50 | .IsRequired() 51 | .HasColumnType("nvarchar(max)"); 52 | 53 | b.HasKey("StudentID"); 54 | 55 | b.ToTable("Students"); 56 | }); 57 | #pragma warning restore 612, 618 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Migrations/20220702105428_mg1.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace CRUDOperationUsingWEBAPI.Migrations 6 | { 7 | public partial class mg1 : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.CreateTable( 12 | name: "Students", 13 | columns: table => new 14 | { 15 | StudentID = table.Column(type: "int", nullable: false) 16 | .Annotation("SqlServer:Identity", "1, 1"), 17 | FirstName = table.Column(type: "nvarchar(max)", nullable: false), 18 | LastName = table.Column(type: "nvarchar(max)", nullable: false), 19 | Email = table.Column(type: "nvarchar(max)", nullable: false), 20 | Gender = table.Column(type: "nvarchar(max)", nullable: false), 21 | Address = table.Column(type: "nvarchar(max)", nullable: true) 22 | }, 23 | constraints: table => 24 | { 25 | table.PrimaryKey("PK_Students", x => x.StudentID); 26 | }); 27 | } 28 | 29 | protected override void Down(MigrationBuilder migrationBuilder) 30 | { 31 | migrationBuilder.DropTable( 32 | name: "Students"); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Migrations/20220702110219_mg2.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CRUDOperationUsingWEBAPI.Context; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace CRUDOperationUsingWEBAPI.Migrations 12 | { 13 | [DbContext(typeof(StudentDBContext))] 14 | [Migration("20220702110219_mg2")] 15 | partial class mg2 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("ProductVersion", "6.0.6") 22 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 23 | 24 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 25 | 26 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Student", b => 27 | { 28 | b.Property("StudentID") 29 | .ValueGeneratedOnAdd() 30 | .HasColumnType("int"); 31 | 32 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StudentID"), 1L, 1); 33 | 34 | b.Property("Address") 35 | .HasColumnType("nvarchar(max)"); 36 | 37 | b.Property("Email") 38 | .IsRequired() 39 | .HasMaxLength(50) 40 | .HasColumnType("nvarchar(50)"); 41 | 42 | b.Property("FirstName") 43 | .IsRequired() 44 | .HasMaxLength(50) 45 | .HasColumnType("nvarchar(50)"); 46 | 47 | b.Property("Gender") 48 | .IsRequired() 49 | .HasMaxLength(5) 50 | .HasColumnType("nvarchar(5)"); 51 | 52 | b.Property("LastName") 53 | .IsRequired() 54 | .HasMaxLength(50) 55 | .HasColumnType("nvarchar(50)"); 56 | 57 | b.HasKey("StudentID"); 58 | 59 | b.ToTable("Students"); 60 | }); 61 | #pragma warning restore 612, 618 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Migrations/20220702110219_mg2.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace CRUDOperationUsingWEBAPI.Migrations 6 | { 7 | public partial class mg2 : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.AlterColumn( 12 | name: "LastName", 13 | table: "Students", 14 | type: "nvarchar(50)", 15 | maxLength: 50, 16 | nullable: false, 17 | oldClrType: typeof(string), 18 | oldType: "nvarchar(max)"); 19 | 20 | migrationBuilder.AlterColumn( 21 | name: "Gender", 22 | table: "Students", 23 | type: "nvarchar(5)", 24 | maxLength: 5, 25 | nullable: false, 26 | oldClrType: typeof(string), 27 | oldType: "nvarchar(max)"); 28 | 29 | migrationBuilder.AlterColumn( 30 | name: "FirstName", 31 | table: "Students", 32 | type: "nvarchar(50)", 33 | maxLength: 50, 34 | nullable: false, 35 | oldClrType: typeof(string), 36 | oldType: "nvarchar(max)"); 37 | 38 | migrationBuilder.AlterColumn( 39 | name: "Email", 40 | table: "Students", 41 | type: "nvarchar(50)", 42 | maxLength: 50, 43 | nullable: false, 44 | oldClrType: typeof(string), 45 | oldType: "nvarchar(max)"); 46 | } 47 | 48 | protected override void Down(MigrationBuilder migrationBuilder) 49 | { 50 | migrationBuilder.AlterColumn( 51 | name: "LastName", 52 | table: "Students", 53 | type: "nvarchar(max)", 54 | nullable: false, 55 | oldClrType: typeof(string), 56 | oldType: "nvarchar(50)", 57 | oldMaxLength: 50); 58 | 59 | migrationBuilder.AlterColumn( 60 | name: "Gender", 61 | table: "Students", 62 | type: "nvarchar(max)", 63 | nullable: false, 64 | oldClrType: typeof(string), 65 | oldType: "nvarchar(5)", 66 | oldMaxLength: 5); 67 | 68 | migrationBuilder.AlterColumn( 69 | name: "FirstName", 70 | table: "Students", 71 | type: "nvarchar(max)", 72 | nullable: false, 73 | oldClrType: typeof(string), 74 | oldType: "nvarchar(50)", 75 | oldMaxLength: 50); 76 | 77 | migrationBuilder.AlterColumn( 78 | name: "Email", 79 | table: "Students", 80 | type: "nvarchar(max)", 81 | nullable: false, 82 | oldClrType: typeof(string), 83 | oldType: "nvarchar(50)", 84 | oldMaxLength: 50); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Migrations/20220703131158_adding_identity.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using CRUDOperationUsingWEBAPI.Context; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | #nullable disable 11 | 12 | namespace CRUDOperationUsingWEBAPI.Migrations 13 | { 14 | [DbContext(typeof(StudentDBContext))] 15 | [Migration("20220703131158_adding_identity")] 16 | partial class adding_identity 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.6") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Student", b => 28 | { 29 | b.Property("StudentID") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("int"); 32 | 33 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StudentID"), 1L, 1); 34 | 35 | b.Property("Address") 36 | .HasColumnType("nvarchar(max)"); 37 | 38 | b.Property("Email") 39 | .IsRequired() 40 | .HasMaxLength(50) 41 | .HasColumnType("nvarchar(50)"); 42 | 43 | b.Property("FirstName") 44 | .IsRequired() 45 | .HasMaxLength(50) 46 | .HasColumnType("nvarchar(50)"); 47 | 48 | b.Property("Gender") 49 | .IsRequired() 50 | .HasMaxLength(5) 51 | .HasColumnType("nvarchar(5)"); 52 | 53 | b.Property("LastName") 54 | .IsRequired() 55 | .HasMaxLength(50) 56 | .HasColumnType("nvarchar(50)"); 57 | 58 | b.HasKey("StudentID"); 59 | 60 | b.ToTable("Students"); 61 | }); 62 | 63 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Users", b => 64 | { 65 | b.Property("Id") 66 | .HasColumnType("nvarchar(450)"); 67 | 68 | b.Property("AccessFailedCount") 69 | .HasColumnType("int"); 70 | 71 | b.Property("Address") 72 | .HasColumnType("nvarchar(max)"); 73 | 74 | b.Property("ConcurrencyStamp") 75 | .IsConcurrencyToken() 76 | .HasColumnType("nvarchar(max)"); 77 | 78 | b.Property("Email") 79 | .HasMaxLength(256) 80 | .HasColumnType("nvarchar(256)"); 81 | 82 | b.Property("EmailConfirmed") 83 | .HasColumnType("bit"); 84 | 85 | b.Property("FirstName") 86 | .IsRequired() 87 | .HasMaxLength(50) 88 | .HasColumnType("nvarchar(50)"); 89 | 90 | b.Property("Gender") 91 | .IsRequired() 92 | .HasMaxLength(6) 93 | .HasColumnType("nvarchar(6)"); 94 | 95 | b.Property("LastName") 96 | .IsRequired() 97 | .HasMaxLength(50) 98 | .HasColumnType("nvarchar(50)"); 99 | 100 | b.Property("LockoutEnabled") 101 | .HasColumnType("bit"); 102 | 103 | b.Property("LockoutEnd") 104 | .HasColumnType("datetimeoffset"); 105 | 106 | b.Property("NormalizedEmail") 107 | .HasMaxLength(256) 108 | .HasColumnType("nvarchar(256)"); 109 | 110 | b.Property("NormalizedUserName") 111 | .HasMaxLength(256) 112 | .HasColumnType("nvarchar(256)"); 113 | 114 | b.Property("PasswordHash") 115 | .HasColumnType("nvarchar(max)"); 116 | 117 | b.Property("PhoneNumber") 118 | .HasColumnType("nvarchar(max)"); 119 | 120 | b.Property("PhoneNumberConfirmed") 121 | .HasColumnType("bit"); 122 | 123 | b.Property("SecurityStamp") 124 | .HasColumnType("nvarchar(max)"); 125 | 126 | b.Property("TwoFactorEnabled") 127 | .HasColumnType("bit"); 128 | 129 | b.Property("UserName") 130 | .HasMaxLength(256) 131 | .HasColumnType("nvarchar(256)"); 132 | 133 | b.HasKey("Id"); 134 | 135 | b.HasIndex("NormalizedEmail") 136 | .HasDatabaseName("EmailIndex"); 137 | 138 | b.HasIndex("NormalizedUserName") 139 | .IsUnique() 140 | .HasDatabaseName("UserNameIndex") 141 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 142 | 143 | b.ToTable("AspNetUsers", (string)null); 144 | }); 145 | 146 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 147 | { 148 | b.Property("Id") 149 | .HasColumnType("nvarchar(450)"); 150 | 151 | b.Property("ConcurrencyStamp") 152 | .IsConcurrencyToken() 153 | .HasColumnType("nvarchar(max)"); 154 | 155 | b.Property("Name") 156 | .HasMaxLength(256) 157 | .HasColumnType("nvarchar(256)"); 158 | 159 | b.Property("NormalizedName") 160 | .HasMaxLength(256) 161 | .HasColumnType("nvarchar(256)"); 162 | 163 | b.HasKey("Id"); 164 | 165 | b.HasIndex("NormalizedName") 166 | .IsUnique() 167 | .HasDatabaseName("RoleNameIndex") 168 | .HasFilter("[NormalizedName] IS NOT NULL"); 169 | 170 | b.ToTable("AspNetRoles", (string)null); 171 | }); 172 | 173 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 174 | { 175 | b.Property("Id") 176 | .ValueGeneratedOnAdd() 177 | .HasColumnType("int"); 178 | 179 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 180 | 181 | b.Property("ClaimType") 182 | .HasColumnType("nvarchar(max)"); 183 | 184 | b.Property("ClaimValue") 185 | .HasColumnType("nvarchar(max)"); 186 | 187 | b.Property("RoleId") 188 | .IsRequired() 189 | .HasColumnType("nvarchar(450)"); 190 | 191 | b.HasKey("Id"); 192 | 193 | b.HasIndex("RoleId"); 194 | 195 | b.ToTable("AspNetRoleClaims", (string)null); 196 | }); 197 | 198 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 199 | { 200 | b.Property("Id") 201 | .ValueGeneratedOnAdd() 202 | .HasColumnType("int"); 203 | 204 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 205 | 206 | b.Property("ClaimType") 207 | .HasColumnType("nvarchar(max)"); 208 | 209 | b.Property("ClaimValue") 210 | .HasColumnType("nvarchar(max)"); 211 | 212 | b.Property("UserId") 213 | .IsRequired() 214 | .HasColumnType("nvarchar(450)"); 215 | 216 | b.HasKey("Id"); 217 | 218 | b.HasIndex("UserId"); 219 | 220 | b.ToTable("AspNetUserClaims", (string)null); 221 | }); 222 | 223 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 224 | { 225 | b.Property("LoginProvider") 226 | .HasColumnType("nvarchar(450)"); 227 | 228 | b.Property("ProviderKey") 229 | .HasColumnType("nvarchar(450)"); 230 | 231 | b.Property("ProviderDisplayName") 232 | .HasColumnType("nvarchar(max)"); 233 | 234 | b.Property("UserId") 235 | .IsRequired() 236 | .HasColumnType("nvarchar(450)"); 237 | 238 | b.HasKey("LoginProvider", "ProviderKey"); 239 | 240 | b.HasIndex("UserId"); 241 | 242 | b.ToTable("AspNetUserLogins", (string)null); 243 | }); 244 | 245 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 246 | { 247 | b.Property("UserId") 248 | .HasColumnType("nvarchar(450)"); 249 | 250 | b.Property("RoleId") 251 | .HasColumnType("nvarchar(450)"); 252 | 253 | b.HasKey("UserId", "RoleId"); 254 | 255 | b.HasIndex("RoleId"); 256 | 257 | b.ToTable("AspNetUserRoles", (string)null); 258 | }); 259 | 260 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 261 | { 262 | b.Property("UserId") 263 | .HasColumnType("nvarchar(450)"); 264 | 265 | b.Property("LoginProvider") 266 | .HasColumnType("nvarchar(450)"); 267 | 268 | b.Property("Name") 269 | .HasColumnType("nvarchar(450)"); 270 | 271 | b.Property("Value") 272 | .HasColumnType("nvarchar(max)"); 273 | 274 | b.HasKey("UserId", "LoginProvider", "Name"); 275 | 276 | b.ToTable("AspNetUserTokens", (string)null); 277 | }); 278 | 279 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 280 | { 281 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 282 | .WithMany() 283 | .HasForeignKey("RoleId") 284 | .OnDelete(DeleteBehavior.Cascade) 285 | .IsRequired(); 286 | }); 287 | 288 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 289 | { 290 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 291 | .WithMany() 292 | .HasForeignKey("UserId") 293 | .OnDelete(DeleteBehavior.Cascade) 294 | .IsRequired(); 295 | }); 296 | 297 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 298 | { 299 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 300 | .WithMany() 301 | .HasForeignKey("UserId") 302 | .OnDelete(DeleteBehavior.Cascade) 303 | .IsRequired(); 304 | }); 305 | 306 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 307 | { 308 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 309 | .WithMany() 310 | .HasForeignKey("RoleId") 311 | .OnDelete(DeleteBehavior.Cascade) 312 | .IsRequired(); 313 | 314 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 315 | .WithMany() 316 | .HasForeignKey("UserId") 317 | .OnDelete(DeleteBehavior.Cascade) 318 | .IsRequired(); 319 | }); 320 | 321 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 322 | { 323 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 324 | .WithMany() 325 | .HasForeignKey("UserId") 326 | .OnDelete(DeleteBehavior.Cascade) 327 | .IsRequired(); 328 | }); 329 | #pragma warning restore 612, 618 330 | } 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /Migrations/20220703131158_adding_identity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace CRUDOperationUsingWEBAPI.Migrations 7 | { 8 | public partial class adding_identity : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "AspNetRoles", 14 | columns: table => new 15 | { 16 | Id = table.Column(type: "nvarchar(450)", nullable: false), 17 | Name = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 18 | NormalizedName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 19 | ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true) 20 | }, 21 | constraints: table => 22 | { 23 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 24 | }); 25 | 26 | migrationBuilder.CreateTable( 27 | name: "AspNetUsers", 28 | columns: table => new 29 | { 30 | Id = table.Column(type: "nvarchar(450)", nullable: false), 31 | FirstName = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), 32 | LastName = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), 33 | Gender = table.Column(type: "nvarchar(6)", maxLength: 6, nullable: false), 34 | Address = table.Column(type: "nvarchar(max)", nullable: true), 35 | UserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 36 | NormalizedUserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 37 | Email = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 38 | NormalizedEmail = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 39 | EmailConfirmed = table.Column(type: "bit", nullable: false), 40 | PasswordHash = table.Column(type: "nvarchar(max)", nullable: true), 41 | SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true), 42 | ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), 43 | PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true), 44 | PhoneNumberConfirmed = table.Column(type: "bit", nullable: false), 45 | TwoFactorEnabled = table.Column(type: "bit", nullable: false), 46 | LockoutEnd = table.Column(type: "datetimeoffset", nullable: true), 47 | LockoutEnabled = table.Column(type: "bit", nullable: false), 48 | AccessFailedCount = table.Column(type: "int", nullable: false) 49 | }, 50 | constraints: table => 51 | { 52 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 53 | }); 54 | 55 | migrationBuilder.CreateTable( 56 | name: "AspNetRoleClaims", 57 | columns: table => new 58 | { 59 | Id = table.Column(type: "int", nullable: false) 60 | .Annotation("SqlServer:Identity", "1, 1"), 61 | RoleId = table.Column(type: "nvarchar(450)", nullable: false), 62 | ClaimType = table.Column(type: "nvarchar(max)", nullable: true), 63 | ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) 64 | }, 65 | constraints: table => 66 | { 67 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 68 | table.ForeignKey( 69 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 70 | column: x => x.RoleId, 71 | principalTable: "AspNetRoles", 72 | principalColumn: "Id", 73 | onDelete: ReferentialAction.Cascade); 74 | }); 75 | 76 | migrationBuilder.CreateTable( 77 | name: "AspNetUserClaims", 78 | columns: table => new 79 | { 80 | Id = table.Column(type: "int", nullable: false) 81 | .Annotation("SqlServer:Identity", "1, 1"), 82 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 83 | ClaimType = table.Column(type: "nvarchar(max)", nullable: true), 84 | ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) 85 | }, 86 | constraints: table => 87 | { 88 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 89 | table.ForeignKey( 90 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 91 | column: x => x.UserId, 92 | principalTable: "AspNetUsers", 93 | principalColumn: "Id", 94 | onDelete: ReferentialAction.Cascade); 95 | }); 96 | 97 | migrationBuilder.CreateTable( 98 | name: "AspNetUserLogins", 99 | columns: table => new 100 | { 101 | LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), 102 | ProviderKey = table.Column(type: "nvarchar(450)", nullable: false), 103 | ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true), 104 | UserId = table.Column(type: "nvarchar(450)", nullable: false) 105 | }, 106 | constraints: table => 107 | { 108 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 109 | table.ForeignKey( 110 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 111 | column: x => x.UserId, 112 | principalTable: "AspNetUsers", 113 | principalColumn: "Id", 114 | onDelete: ReferentialAction.Cascade); 115 | }); 116 | 117 | migrationBuilder.CreateTable( 118 | name: "AspNetUserRoles", 119 | columns: table => new 120 | { 121 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 122 | RoleId = table.Column(type: "nvarchar(450)", nullable: false) 123 | }, 124 | constraints: table => 125 | { 126 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 127 | table.ForeignKey( 128 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 129 | column: x => x.RoleId, 130 | principalTable: "AspNetRoles", 131 | principalColumn: "Id", 132 | onDelete: ReferentialAction.Cascade); 133 | table.ForeignKey( 134 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 135 | column: x => x.UserId, 136 | principalTable: "AspNetUsers", 137 | principalColumn: "Id", 138 | onDelete: ReferentialAction.Cascade); 139 | }); 140 | 141 | migrationBuilder.CreateTable( 142 | name: "AspNetUserTokens", 143 | columns: table => new 144 | { 145 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 146 | LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), 147 | Name = table.Column(type: "nvarchar(450)", nullable: false), 148 | Value = table.Column(type: "nvarchar(max)", nullable: true) 149 | }, 150 | constraints: table => 151 | { 152 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 153 | table.ForeignKey( 154 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 155 | column: x => x.UserId, 156 | principalTable: "AspNetUsers", 157 | principalColumn: "Id", 158 | onDelete: ReferentialAction.Cascade); 159 | }); 160 | 161 | migrationBuilder.CreateIndex( 162 | name: "IX_AspNetRoleClaims_RoleId", 163 | table: "AspNetRoleClaims", 164 | column: "RoleId"); 165 | 166 | migrationBuilder.CreateIndex( 167 | name: "RoleNameIndex", 168 | table: "AspNetRoles", 169 | column: "NormalizedName", 170 | unique: true, 171 | filter: "[NormalizedName] IS NOT NULL"); 172 | 173 | migrationBuilder.CreateIndex( 174 | name: "IX_AspNetUserClaims_UserId", 175 | table: "AspNetUserClaims", 176 | column: "UserId"); 177 | 178 | migrationBuilder.CreateIndex( 179 | name: "IX_AspNetUserLogins_UserId", 180 | table: "AspNetUserLogins", 181 | column: "UserId"); 182 | 183 | migrationBuilder.CreateIndex( 184 | name: "IX_AspNetUserRoles_RoleId", 185 | table: "AspNetUserRoles", 186 | column: "RoleId"); 187 | 188 | migrationBuilder.CreateIndex( 189 | name: "EmailIndex", 190 | table: "AspNetUsers", 191 | column: "NormalizedEmail"); 192 | 193 | migrationBuilder.CreateIndex( 194 | name: "UserNameIndex", 195 | table: "AspNetUsers", 196 | column: "NormalizedUserName", 197 | unique: true, 198 | filter: "[NormalizedUserName] IS NOT NULL"); 199 | } 200 | 201 | protected override void Down(MigrationBuilder migrationBuilder) 202 | { 203 | migrationBuilder.DropTable( 204 | name: "AspNetRoleClaims"); 205 | 206 | migrationBuilder.DropTable( 207 | name: "AspNetUserClaims"); 208 | 209 | migrationBuilder.DropTable( 210 | name: "AspNetUserLogins"); 211 | 212 | migrationBuilder.DropTable( 213 | name: "AspNetUserRoles"); 214 | 215 | migrationBuilder.DropTable( 216 | name: "AspNetUserTokens"); 217 | 218 | migrationBuilder.DropTable( 219 | name: "AspNetRoles"); 220 | 221 | migrationBuilder.DropTable( 222 | name: "AspNetUsers"); 223 | } 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /Migrations/20220724133121_mp-3.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using CRUDOperationUsingWEBAPI.Context; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | #nullable disable 11 | 12 | namespace CRUDOperationUsingWEBAPI.Migrations 13 | { 14 | [DbContext(typeof(StudentDBContext))] 15 | [Migration("20220724133121_mp-3")] 16 | partial class mp3 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.6") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Student", b => 28 | { 29 | b.Property("StudentID") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("int"); 32 | 33 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StudentID"), 1L, 1); 34 | 35 | b.Property("Address") 36 | .HasColumnType("nvarchar(max)"); 37 | 38 | b.Property("Email") 39 | .IsRequired() 40 | .HasMaxLength(50) 41 | .HasColumnType("nvarchar(50)"); 42 | 43 | b.Property("FirstName") 44 | .IsRequired() 45 | .HasMaxLength(50) 46 | .HasColumnType("nvarchar(50)"); 47 | 48 | b.Property("Gender") 49 | .IsRequired() 50 | .HasMaxLength(10) 51 | .HasColumnType("nvarchar(10)"); 52 | 53 | b.Property("LastName") 54 | .IsRequired() 55 | .HasMaxLength(50) 56 | .HasColumnType("nvarchar(50)"); 57 | 58 | b.HasKey("StudentID"); 59 | 60 | b.ToTable("Students"); 61 | }); 62 | 63 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Users", b => 64 | { 65 | b.Property("Id") 66 | .HasColumnType("nvarchar(450)"); 67 | 68 | b.Property("AccessFailedCount") 69 | .HasColumnType("int"); 70 | 71 | b.Property("Address") 72 | .HasColumnType("nvarchar(max)"); 73 | 74 | b.Property("ConcurrencyStamp") 75 | .IsConcurrencyToken() 76 | .HasColumnType("nvarchar(max)"); 77 | 78 | b.Property("Email") 79 | .HasMaxLength(256) 80 | .HasColumnType("nvarchar(256)"); 81 | 82 | b.Property("EmailConfirmed") 83 | .HasColumnType("bit"); 84 | 85 | b.Property("FirstName") 86 | .IsRequired() 87 | .HasMaxLength(50) 88 | .HasColumnType("nvarchar(50)"); 89 | 90 | b.Property("Gender") 91 | .IsRequired() 92 | .HasMaxLength(6) 93 | .HasColumnType("nvarchar(6)"); 94 | 95 | b.Property("LastName") 96 | .IsRequired() 97 | .HasMaxLength(50) 98 | .HasColumnType("nvarchar(50)"); 99 | 100 | b.Property("LockoutEnabled") 101 | .HasColumnType("bit"); 102 | 103 | b.Property("LockoutEnd") 104 | .HasColumnType("datetimeoffset"); 105 | 106 | b.Property("NormalizedEmail") 107 | .HasMaxLength(256) 108 | .HasColumnType("nvarchar(256)"); 109 | 110 | b.Property("NormalizedUserName") 111 | .HasMaxLength(256) 112 | .HasColumnType("nvarchar(256)"); 113 | 114 | b.Property("PasswordHash") 115 | .HasColumnType("nvarchar(max)"); 116 | 117 | b.Property("PhoneNumber") 118 | .HasColumnType("nvarchar(max)"); 119 | 120 | b.Property("PhoneNumberConfirmed") 121 | .HasColumnType("bit"); 122 | 123 | b.Property("SecurityStamp") 124 | .HasColumnType("nvarchar(max)"); 125 | 126 | b.Property("TwoFactorEnabled") 127 | .HasColumnType("bit"); 128 | 129 | b.Property("UserName") 130 | .HasMaxLength(256) 131 | .HasColumnType("nvarchar(256)"); 132 | 133 | b.HasKey("Id"); 134 | 135 | b.HasIndex("NormalizedEmail") 136 | .HasDatabaseName("EmailIndex"); 137 | 138 | b.HasIndex("NormalizedUserName") 139 | .IsUnique() 140 | .HasDatabaseName("UserNameIndex") 141 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 142 | 143 | b.ToTable("AspNetUsers", (string)null); 144 | }); 145 | 146 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 147 | { 148 | b.Property("Id") 149 | .HasColumnType("nvarchar(450)"); 150 | 151 | b.Property("ConcurrencyStamp") 152 | .IsConcurrencyToken() 153 | .HasColumnType("nvarchar(max)"); 154 | 155 | b.Property("Name") 156 | .HasMaxLength(256) 157 | .HasColumnType("nvarchar(256)"); 158 | 159 | b.Property("NormalizedName") 160 | .HasMaxLength(256) 161 | .HasColumnType("nvarchar(256)"); 162 | 163 | b.HasKey("Id"); 164 | 165 | b.HasIndex("NormalizedName") 166 | .IsUnique() 167 | .HasDatabaseName("RoleNameIndex") 168 | .HasFilter("[NormalizedName] IS NOT NULL"); 169 | 170 | b.ToTable("AspNetRoles", (string)null); 171 | }); 172 | 173 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 174 | { 175 | b.Property("Id") 176 | .ValueGeneratedOnAdd() 177 | .HasColumnType("int"); 178 | 179 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 180 | 181 | b.Property("ClaimType") 182 | .HasColumnType("nvarchar(max)"); 183 | 184 | b.Property("ClaimValue") 185 | .HasColumnType("nvarchar(max)"); 186 | 187 | b.Property("RoleId") 188 | .IsRequired() 189 | .HasColumnType("nvarchar(450)"); 190 | 191 | b.HasKey("Id"); 192 | 193 | b.HasIndex("RoleId"); 194 | 195 | b.ToTable("AspNetRoleClaims", (string)null); 196 | }); 197 | 198 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 199 | { 200 | b.Property("Id") 201 | .ValueGeneratedOnAdd() 202 | .HasColumnType("int"); 203 | 204 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 205 | 206 | b.Property("ClaimType") 207 | .HasColumnType("nvarchar(max)"); 208 | 209 | b.Property("ClaimValue") 210 | .HasColumnType("nvarchar(max)"); 211 | 212 | b.Property("UserId") 213 | .IsRequired() 214 | .HasColumnType("nvarchar(450)"); 215 | 216 | b.HasKey("Id"); 217 | 218 | b.HasIndex("UserId"); 219 | 220 | b.ToTable("AspNetUserClaims", (string)null); 221 | }); 222 | 223 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 224 | { 225 | b.Property("LoginProvider") 226 | .HasColumnType("nvarchar(450)"); 227 | 228 | b.Property("ProviderKey") 229 | .HasColumnType("nvarchar(450)"); 230 | 231 | b.Property("ProviderDisplayName") 232 | .HasColumnType("nvarchar(max)"); 233 | 234 | b.Property("UserId") 235 | .IsRequired() 236 | .HasColumnType("nvarchar(450)"); 237 | 238 | b.HasKey("LoginProvider", "ProviderKey"); 239 | 240 | b.HasIndex("UserId"); 241 | 242 | b.ToTable("AspNetUserLogins", (string)null); 243 | }); 244 | 245 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 246 | { 247 | b.Property("UserId") 248 | .HasColumnType("nvarchar(450)"); 249 | 250 | b.Property("RoleId") 251 | .HasColumnType("nvarchar(450)"); 252 | 253 | b.HasKey("UserId", "RoleId"); 254 | 255 | b.HasIndex("RoleId"); 256 | 257 | b.ToTable("AspNetUserRoles", (string)null); 258 | }); 259 | 260 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 261 | { 262 | b.Property("UserId") 263 | .HasColumnType("nvarchar(450)"); 264 | 265 | b.Property("LoginProvider") 266 | .HasColumnType("nvarchar(450)"); 267 | 268 | b.Property("Name") 269 | .HasColumnType("nvarchar(450)"); 270 | 271 | b.Property("Value") 272 | .HasColumnType("nvarchar(max)"); 273 | 274 | b.HasKey("UserId", "LoginProvider", "Name"); 275 | 276 | b.ToTable("AspNetUserTokens", (string)null); 277 | }); 278 | 279 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 280 | { 281 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 282 | .WithMany() 283 | .HasForeignKey("RoleId") 284 | .OnDelete(DeleteBehavior.Cascade) 285 | .IsRequired(); 286 | }); 287 | 288 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 289 | { 290 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 291 | .WithMany() 292 | .HasForeignKey("UserId") 293 | .OnDelete(DeleteBehavior.Cascade) 294 | .IsRequired(); 295 | }); 296 | 297 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 298 | { 299 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 300 | .WithMany() 301 | .HasForeignKey("UserId") 302 | .OnDelete(DeleteBehavior.Cascade) 303 | .IsRequired(); 304 | }); 305 | 306 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 307 | { 308 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 309 | .WithMany() 310 | .HasForeignKey("RoleId") 311 | .OnDelete(DeleteBehavior.Cascade) 312 | .IsRequired(); 313 | 314 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 315 | .WithMany() 316 | .HasForeignKey("UserId") 317 | .OnDelete(DeleteBehavior.Cascade) 318 | .IsRequired(); 319 | }); 320 | 321 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 322 | { 323 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 324 | .WithMany() 325 | .HasForeignKey("UserId") 326 | .OnDelete(DeleteBehavior.Cascade) 327 | .IsRequired(); 328 | }); 329 | #pragma warning restore 612, 618 330 | } 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /Migrations/20220724133121_mp-3.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace CRUDOperationUsingWEBAPI.Migrations 6 | { 7 | public partial class mp3 : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.AlterColumn( 12 | name: "Gender", 13 | table: "Students", 14 | type: "nvarchar(10)", 15 | maxLength: 10, 16 | nullable: false, 17 | oldClrType: typeof(string), 18 | oldType: "nvarchar(5)", 19 | oldMaxLength: 5); 20 | } 21 | 22 | protected override void Down(MigrationBuilder migrationBuilder) 23 | { 24 | migrationBuilder.AlterColumn( 25 | name: "Gender", 26 | table: "Students", 27 | type: "nvarchar(5)", 28 | maxLength: 5, 29 | nullable: false, 30 | oldClrType: typeof(string), 31 | oldType: "nvarchar(10)", 32 | oldMaxLength: 10); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Migrations/StudentDBContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using CRUDOperationUsingWEBAPI.Context; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace CRUDOperationUsingWEBAPI.Migrations 12 | { 13 | [DbContext(typeof(StudentDBContext))] 14 | partial class StudentDBContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.6") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 24 | 25 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Student", b => 26 | { 27 | b.Property("StudentID") 28 | .ValueGeneratedOnAdd() 29 | .HasColumnType("int"); 30 | 31 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StudentID"), 1L, 1); 32 | 33 | b.Property("Address") 34 | .HasColumnType("nvarchar(max)"); 35 | 36 | b.Property("Email") 37 | .IsRequired() 38 | .HasMaxLength(50) 39 | .HasColumnType("nvarchar(50)"); 40 | 41 | b.Property("FirstName") 42 | .IsRequired() 43 | .HasMaxLength(50) 44 | .HasColumnType("nvarchar(50)"); 45 | 46 | b.Property("Gender") 47 | .IsRequired() 48 | .HasMaxLength(10) 49 | .HasColumnType("nvarchar(10)"); 50 | 51 | b.Property("LastName") 52 | .IsRequired() 53 | .HasMaxLength(50) 54 | .HasColumnType("nvarchar(50)"); 55 | 56 | b.HasKey("StudentID"); 57 | 58 | b.ToTable("Students"); 59 | }); 60 | 61 | modelBuilder.Entity("CRUDOperationUsingWEBAPI.Data.Users", b => 62 | { 63 | b.Property("Id") 64 | .HasColumnType("nvarchar(450)"); 65 | 66 | b.Property("AccessFailedCount") 67 | .HasColumnType("int"); 68 | 69 | b.Property("Address") 70 | .HasColumnType("nvarchar(max)"); 71 | 72 | b.Property("ConcurrencyStamp") 73 | .IsConcurrencyToken() 74 | .HasColumnType("nvarchar(max)"); 75 | 76 | b.Property("Email") 77 | .HasMaxLength(256) 78 | .HasColumnType("nvarchar(256)"); 79 | 80 | b.Property("EmailConfirmed") 81 | .HasColumnType("bit"); 82 | 83 | b.Property("FirstName") 84 | .IsRequired() 85 | .HasMaxLength(50) 86 | .HasColumnType("nvarchar(50)"); 87 | 88 | b.Property("Gender") 89 | .IsRequired() 90 | .HasMaxLength(6) 91 | .HasColumnType("nvarchar(6)"); 92 | 93 | b.Property("LastName") 94 | .IsRequired() 95 | .HasMaxLength(50) 96 | .HasColumnType("nvarchar(50)"); 97 | 98 | b.Property("LockoutEnabled") 99 | .HasColumnType("bit"); 100 | 101 | b.Property("LockoutEnd") 102 | .HasColumnType("datetimeoffset"); 103 | 104 | b.Property("NormalizedEmail") 105 | .HasMaxLength(256) 106 | .HasColumnType("nvarchar(256)"); 107 | 108 | b.Property("NormalizedUserName") 109 | .HasMaxLength(256) 110 | .HasColumnType("nvarchar(256)"); 111 | 112 | b.Property("PasswordHash") 113 | .HasColumnType("nvarchar(max)"); 114 | 115 | b.Property("PhoneNumber") 116 | .HasColumnType("nvarchar(max)"); 117 | 118 | b.Property("PhoneNumberConfirmed") 119 | .HasColumnType("bit"); 120 | 121 | b.Property("SecurityStamp") 122 | .HasColumnType("nvarchar(max)"); 123 | 124 | b.Property("TwoFactorEnabled") 125 | .HasColumnType("bit"); 126 | 127 | b.Property("UserName") 128 | .HasMaxLength(256) 129 | .HasColumnType("nvarchar(256)"); 130 | 131 | b.HasKey("Id"); 132 | 133 | b.HasIndex("NormalizedEmail") 134 | .HasDatabaseName("EmailIndex"); 135 | 136 | b.HasIndex("NormalizedUserName") 137 | .IsUnique() 138 | .HasDatabaseName("UserNameIndex") 139 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 140 | 141 | b.ToTable("AspNetUsers", (string)null); 142 | }); 143 | 144 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 145 | { 146 | b.Property("Id") 147 | .HasColumnType("nvarchar(450)"); 148 | 149 | b.Property("ConcurrencyStamp") 150 | .IsConcurrencyToken() 151 | .HasColumnType("nvarchar(max)"); 152 | 153 | b.Property("Name") 154 | .HasMaxLength(256) 155 | .HasColumnType("nvarchar(256)"); 156 | 157 | b.Property("NormalizedName") 158 | .HasMaxLength(256) 159 | .HasColumnType("nvarchar(256)"); 160 | 161 | b.HasKey("Id"); 162 | 163 | b.HasIndex("NormalizedName") 164 | .IsUnique() 165 | .HasDatabaseName("RoleNameIndex") 166 | .HasFilter("[NormalizedName] IS NOT NULL"); 167 | 168 | b.ToTable("AspNetRoles", (string)null); 169 | }); 170 | 171 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 172 | { 173 | b.Property("Id") 174 | .ValueGeneratedOnAdd() 175 | .HasColumnType("int"); 176 | 177 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 178 | 179 | b.Property("ClaimType") 180 | .HasColumnType("nvarchar(max)"); 181 | 182 | b.Property("ClaimValue") 183 | .HasColumnType("nvarchar(max)"); 184 | 185 | b.Property("RoleId") 186 | .IsRequired() 187 | .HasColumnType("nvarchar(450)"); 188 | 189 | b.HasKey("Id"); 190 | 191 | b.HasIndex("RoleId"); 192 | 193 | b.ToTable("AspNetRoleClaims", (string)null); 194 | }); 195 | 196 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 197 | { 198 | b.Property("Id") 199 | .ValueGeneratedOnAdd() 200 | .HasColumnType("int"); 201 | 202 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 203 | 204 | b.Property("ClaimType") 205 | .HasColumnType("nvarchar(max)"); 206 | 207 | b.Property("ClaimValue") 208 | .HasColumnType("nvarchar(max)"); 209 | 210 | b.Property("UserId") 211 | .IsRequired() 212 | .HasColumnType("nvarchar(450)"); 213 | 214 | b.HasKey("Id"); 215 | 216 | b.HasIndex("UserId"); 217 | 218 | b.ToTable("AspNetUserClaims", (string)null); 219 | }); 220 | 221 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 222 | { 223 | b.Property("LoginProvider") 224 | .HasColumnType("nvarchar(450)"); 225 | 226 | b.Property("ProviderKey") 227 | .HasColumnType("nvarchar(450)"); 228 | 229 | b.Property("ProviderDisplayName") 230 | .HasColumnType("nvarchar(max)"); 231 | 232 | b.Property("UserId") 233 | .IsRequired() 234 | .HasColumnType("nvarchar(450)"); 235 | 236 | b.HasKey("LoginProvider", "ProviderKey"); 237 | 238 | b.HasIndex("UserId"); 239 | 240 | b.ToTable("AspNetUserLogins", (string)null); 241 | }); 242 | 243 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 244 | { 245 | b.Property("UserId") 246 | .HasColumnType("nvarchar(450)"); 247 | 248 | b.Property("RoleId") 249 | .HasColumnType("nvarchar(450)"); 250 | 251 | b.HasKey("UserId", "RoleId"); 252 | 253 | b.HasIndex("RoleId"); 254 | 255 | b.ToTable("AspNetUserRoles", (string)null); 256 | }); 257 | 258 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 259 | { 260 | b.Property("UserId") 261 | .HasColumnType("nvarchar(450)"); 262 | 263 | b.Property("LoginProvider") 264 | .HasColumnType("nvarchar(450)"); 265 | 266 | b.Property("Name") 267 | .HasColumnType("nvarchar(450)"); 268 | 269 | b.Property("Value") 270 | .HasColumnType("nvarchar(max)"); 271 | 272 | b.HasKey("UserId", "LoginProvider", "Name"); 273 | 274 | b.ToTable("AspNetUserTokens", (string)null); 275 | }); 276 | 277 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 278 | { 279 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 280 | .WithMany() 281 | .HasForeignKey("RoleId") 282 | .OnDelete(DeleteBehavior.Cascade) 283 | .IsRequired(); 284 | }); 285 | 286 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 287 | { 288 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 289 | .WithMany() 290 | .HasForeignKey("UserId") 291 | .OnDelete(DeleteBehavior.Cascade) 292 | .IsRequired(); 293 | }); 294 | 295 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 296 | { 297 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 298 | .WithMany() 299 | .HasForeignKey("UserId") 300 | .OnDelete(DeleteBehavior.Cascade) 301 | .IsRequired(); 302 | }); 303 | 304 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 305 | { 306 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 307 | .WithMany() 308 | .HasForeignKey("RoleId") 309 | .OnDelete(DeleteBehavior.Cascade) 310 | .IsRequired(); 311 | 312 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 313 | .WithMany() 314 | .HasForeignKey("UserId") 315 | .OnDelete(DeleteBehavior.Cascade) 316 | .IsRequired(); 317 | }); 318 | 319 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 320 | { 321 | b.HasOne("CRUDOperationUsingWEBAPI.Data.Users", null) 322 | .WithMany() 323 | .HasForeignKey("UserId") 324 | .OnDelete(DeleteBehavior.Cascade) 325 | .IsRequired(); 326 | }); 327 | #pragma warning restore 612, 618 328 | } 329 | } 330 | } 331 | -------------------------------------------------------------------------------- /Models/AssignRoleToUserDTO.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class AssignRoleToUserDTO 4 | { 5 | public string Email { get; set; } 6 | public string RoleName { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Models/AuthenticateUser.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class AuthenticateUser 4 | { 5 | public string UserName { get; set; } 6 | public string Password { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Models/AuthenticationResponse.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class AuthenticationResponse 4 | { 5 | public string? AccessToken { get; set; } 6 | public string? RefreshToken { get; set; } 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Models/CreateRoleDTO.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class CreateRoleDTO 4 | { 5 | public string RoleName { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Models/DeleteStudentDTO.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class DeleteStudentDTO 4 | { 5 | public int StudentID { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Models/DeleteUserDTO.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class DeleteUserDTO 4 | { 5 | public string Email { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Models/ErrorResponse.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace CRUDOperationUsingWEBAPI.Models 4 | { 5 | public class ErrorResponse 6 | { 7 | public static BadRequestObjectResult ReturnErrorResponse(string errorMessage) 8 | { 9 | return new BadRequestObjectResult(new MainResponse 10 | { 11 | ErrorMessage = errorMessage, 12 | IsSuccess = true 13 | }); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Models/MainResponse.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class MainResponse 4 | { 5 | public bool IsSuccess { get; set; } 6 | public string? ErrorMessage { get; set; } 7 | public object? Content { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Models/RefreshTokenRequest.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class RefreshTokenRequest 4 | { 5 | public string AccessToken { get; set; } 6 | public string RefreshToken { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Models/RegisterUserDTO.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class RegisterUserDTO 4 | { 5 | public string FirstName { get; set; } 6 | public string LastName { get; set; } 7 | public string Gender { get; set; } 8 | public string Password { get; set; } 9 | public string Email { get; set; } 10 | public string? Address { get; set; } 11 | public string UserAvatar { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Models/StudentDTO.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class StudentDTO 4 | { 5 | public int StudentID { get; set; } 6 | public string FirstName { get; set; } = null!; 7 | public string LastName { get; set; } = null!; 8 | public string Email { get; set; } = null!; 9 | public string Gender { get; set; } = null!; 10 | public string? Address { get; set; } 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Models/UpdateStudentDTO.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI.Models 2 | { 3 | public class UpdateStudentDTO 4 | { 5 | public int StudentID { get; set; } 6 | public string FirstName { get; set; } = null!; 7 | public string LastName { get; set; } = null!; 8 | public string? Address { get; set; } 9 | public string Gender { get; set; } 10 | public string Email { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using CRUDOperationUsingWEBAPI.Context; 2 | using CRUDOperationUsingWEBAPI.Data; 3 | using CRUDOperationUsingWEBAPI.Services; 4 | using Microsoft.AspNetCore.Authentication.JwtBearer; 5 | using Microsoft.AspNetCore.Identity; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.Extensions.FileProviders; 8 | using Microsoft.IdentityModel.Tokens; 9 | using Microsoft.OpenApi.Models; 10 | using System.Text; 11 | 12 | var builder = WebApplication.CreateBuilder(args); 13 | 14 | var connectionSTring = builder.Configuration.GetConnectionString("StudentDB"); 15 | builder.Services.AddDbContext(options => options.UseSqlServer(connectionSTring)); 16 | builder.Services.AddScoped(); 17 | builder.Services.AddIdentity().AddEntityFrameworkStores(); 18 | builder.Services.AddSwaggerGen(swagger => 19 | { 20 | swagger.SwaggerDoc("v1", 21 | new OpenApiInfo 22 | { 23 | Title = "API Title", 24 | Version = "V1", 25 | Description = "API Description" 26 | }); 27 | 28 | var securitySchema = new OpenApiSecurityScheme 29 | { 30 | Description = "Authorization header using the Bearer scheme. Example \"Authorization: Bearer {token}\"", 31 | Name = "Authorization", 32 | In = ParameterLocation.Header, 33 | Type = SecuritySchemeType.Http, 34 | Scheme = "Bearer", 35 | Reference = new OpenApiReference 36 | { 37 | Type = ReferenceType.SecurityScheme, 38 | Id = "Bearer" 39 | } 40 | }; 41 | swagger.AddSecurityDefinition(securitySchema.Reference.Id, securitySchema); 42 | swagger.AddSecurityRequirement(new OpenApiSecurityRequirement 43 | { 44 | {securitySchema,Array.Empty() } 45 | }); 46 | }); 47 | builder.Services.AddAuthentication(f => 48 | { 49 | f.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 50 | f.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 51 | }).AddJwtBearer(k => 52 | { 53 | var Key = Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"]); 54 | k.SaveToken = true; 55 | k.TokenValidationParameters = new TokenValidationParameters 56 | { 57 | ValidateIssuer = true, 58 | ValidateAudience = true, 59 | ValidateLifetime = true, 60 | ValidateIssuerSigningKey = true, 61 | ValidIssuer = builder.Configuration["JWT:Issuer"], 62 | ValidAudience = builder.Configuration["JWT:Audience"], 63 | IssuerSigningKey = new SymmetricSecurityKey(Key), 64 | ClockSkew = TimeSpan.Zero 65 | }; 66 | 67 | }); 68 | // Add services to the container. 69 | 70 | builder.Services.AddControllers(); 71 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 72 | builder.Services.AddEndpointsApiExplorer(); 73 | builder.Services.AddSwaggerGen(); 74 | 75 | var app = builder.Build(); 76 | // Configure the HTTP request pipeline. 77 | if (app.Environment.IsDevelopment()) 78 | { 79 | app.UseSwagger(); 80 | app.UseSwaggerUI(); 81 | } 82 | 83 | app.UseStaticFiles(new StaticFileOptions 84 | { 85 | FileProvider = new PhysicalFileProvider( 86 | Path.Combine(Directory.GetCurrentDirectory(), "Images")), 87 | RequestPath = "/Images" 88 | }); 89 | 90 | app.UseHttpsRedirection(); 91 | 92 | app.UseAuthentication(); 93 | app.UseAuthorization(); 94 | app.MapControllers(); 95 | 96 | app.Run(); 97 | -------------------------------------------------------------------------------- /Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://192.168.0.185:8188", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "CRUDOperationUsingWEBAPI": { 13 | "commandName": "Project", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | }, 19 | "applicationUrl": "http://192.168.0.185:80", 20 | "dotnetRunMessages": true 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Services/IStudentService.cs: -------------------------------------------------------------------------------- 1 | using CRUDOperationUsingWEBAPI.Models; 2 | 3 | namespace CRUDOperationUsingWEBAPI.Services 4 | { 5 | public interface IStudentService 6 | { 7 | Task AddStudent(StudentDTO studentDTO); 8 | Task UpdateStudent(UpdateStudentDTO studentDTO); 9 | Task DeleteStudent(DeleteStudentDTO studentDTO); 10 | Task GetAllStudent(); 11 | Task GetStudentByStudentID(int studentID); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Services/StudentService.cs: -------------------------------------------------------------------------------- 1 | using CRUDOperationUsingWEBAPI.Context; 2 | using CRUDOperationUsingWEBAPI.Data; 3 | using CRUDOperationUsingWEBAPI.Models; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace CRUDOperationUsingWEBAPI.Services 7 | { 8 | public class StudentService : IStudentService 9 | { 10 | private readonly StudentDBContext _context; 11 | public StudentService(StudentDBContext context) 12 | { 13 | _context = context; 14 | } 15 | 16 | public async Task AddStudent(StudentDTO studentDTO) 17 | { 18 | var response = new MainResponse(); 19 | try 20 | { 21 | if (_context.Students.Any(f => f.Email.ToLower() == studentDTO.Email.ToLower())) 22 | { 23 | response.ErrorMessage = "Student is already exist with this email"; 24 | response.IsSuccess = false; 25 | } 26 | else 27 | { 28 | await _context.AddAsync(new Student 29 | { 30 | Email = studentDTO.Email, 31 | Address = studentDTO.Address, 32 | FirstName = studentDTO.FirstName, 33 | Gender = studentDTO.Gender, 34 | LastName = studentDTO.LastName, 35 | }); 36 | await _context.SaveChangesAsync(); 37 | 38 | response.IsSuccess = true; 39 | response.Content = "Student Added"; 40 | } 41 | 42 | 43 | } 44 | catch (Exception ex) 45 | { 46 | response.ErrorMessage = ex.Message; 47 | response.IsSuccess = false; 48 | } 49 | 50 | return response; 51 | } 52 | 53 | public async Task DeleteStudent(DeleteStudentDTO studentDTO) 54 | { 55 | var response = new MainResponse(); 56 | try 57 | { 58 | if (studentDTO.StudentID < 0) 59 | { 60 | response.ErrorMessage = "Please pass student ID"; 61 | return response; 62 | } 63 | 64 | var existingStudent = _context.Students.Where(f => f.StudentID == studentDTO.StudentID).FirstOrDefault(); 65 | 66 | if (existingStudent != null) 67 | { 68 | _context.Remove(existingStudent); 69 | await _context.SaveChangesAsync(); 70 | 71 | response.IsSuccess = true; 72 | response.Content = "Student Info Deleted"; 73 | } 74 | else 75 | { 76 | response.IsSuccess = false; 77 | response.Content = "Student not found with specify student ID"; 78 | } 79 | 80 | } 81 | catch (Exception ex) 82 | { 83 | response.ErrorMessage = ex.Message; 84 | response.IsSuccess = false; 85 | } 86 | 87 | return response; 88 | } 89 | 90 | public async Task GetAllStudent() 91 | { 92 | var response = new MainResponse(); 93 | try 94 | { 95 | response.Content = await _context.Students.ToListAsync(); 96 | response.IsSuccess = true; 97 | } 98 | catch (Exception ex) 99 | { 100 | response.ErrorMessage = ex.Message; 101 | response.IsSuccess = false; 102 | } 103 | return response; 104 | } 105 | 106 | public async Task GetStudentByStudentID(int studentID) 107 | { 108 | var response = new MainResponse(); 109 | try 110 | { 111 | response.Content = 112 | await _context.Students.Where(f => f.StudentID == studentID).FirstOrDefaultAsync(); 113 | response.IsSuccess = true; 114 | } 115 | catch (Exception ex) 116 | { 117 | response.ErrorMessage = ex.Message; 118 | response.IsSuccess = false; 119 | } 120 | return response; 121 | } 122 | 123 | public async Task UpdateStudent(UpdateStudentDTO studentDTO) 124 | { 125 | var response = new MainResponse(); 126 | try 127 | { 128 | if (studentDTO.StudentID < 0) 129 | { 130 | response.ErrorMessage = "Please pass student ID"; 131 | return response; 132 | } 133 | 134 | var existingStudent = _context.Students.Where(f => f.StudentID == studentDTO.StudentID).FirstOrDefault(); 135 | 136 | if (existingStudent != null) 137 | { 138 | existingStudent.Address = studentDTO.Address; 139 | existingStudent.FirstName = studentDTO.FirstName; 140 | existingStudent.LastName = studentDTO.LastName; 141 | existingStudent.Email = studentDTO.Email; 142 | existingStudent.Gender = studentDTO.Gender; 143 | await _context.SaveChangesAsync(); 144 | 145 | response.IsSuccess = true; 146 | response.Content = "Record Updated"; 147 | } 148 | else 149 | { 150 | response.IsSuccess = false; 151 | response.Content = "Student not found with specify student ID"; 152 | } 153 | 154 | } 155 | catch (Exception ex) 156 | { 157 | response.ErrorMessage = ex.Message; 158 | response.IsSuccess = false; 159 | } 160 | 161 | return response; 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace CRUDOperationUsingWEBAPI 2 | { 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "ConnectionStrings": { "StudentDB": "Server=.\\;Database=StudentDB;Trusted_Connection=True;" }, 9 | "AllowedHosts": "*", 10 | "JWT": { 11 | "Key": "HereIstheUniqueKeyForValdiation", 12 | "Issuer": "https://xamarincodingtutorial.blogspot.com", 13 | "Audience": "xamarincodingtutorial.info" 14 | } 15 | } 16 | --------------------------------------------------------------------------------