Readdy Write  
0,00 €
Your View Money
Views: Count
Self 20% 0
Your Content 60% 0

Users by Links 0
u1*(Content+Views) 10% 0
Follow-Follower 0
s2*(Income) 5% 0

Count
Followers 0
Login Register as User

Web Api Client-Server 20180704: Part 7) Web API Controller

04.07.2018 (👁1173)


Platform: Asp.Net Core 2 MVC

WebApi, Webserver

Sprache: C#

ProjectsController.cs

Web-API Controller

Der WebApi Controller wird gesichert mit Java Web Tokens JwtToken JwtBearer.

Beim Aufbau einer Verbindung zur Web API mit mit Authorize AuthenticationSchemes zunächst der Zugriff geprüft über die Startup.cs Einstellungen.

Die API Standard Methoden httpGet, HttpPost

HttpGet Index erstellt eine Übersichtsliste aller eigener Einträge

HttpPost Create erstellt neue Einträge, hier Projekte

HttpDelete(id) Delete löscht den Angegebenen Datensatz

Get_UserID prüft, ob der aktuelle User die Berechtigungen hat

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Security.Claims;

using System.Threading.Tasks;

using Freelance.Data;

using Freelance.Models;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Http;    //*HttpContent

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Newtonsoft.Json.Linq;

 

namespace Freelance.Controllers.api

{

    [Authorize(AuthenticationSchemes = "JwtBearer")]    //*goes to startup ConfigureServices.AddAuthentication->AddJwtBearer(..)

    [Produces("application/json")]

    [Route("api/Projects")]

    public class ProjectsController : Controller

    {

        //--------------< Class: ApiController >---------------------

        #region Controller Init

        private readonly ApplicationDbContext _dbContext;

        

        public ProjectsController(ApplicationDbContext dbContext)

        {

            //----< Init: Controller >----

            _dbContext = dbContext;

            //----</ Init: Controller >----

        }

        #endregion

 

 

      

 

        // GET: /api/index

        public async Task<List<ProjectModel>> Index()

        {

            //-------------< Index >------------- 

            //< get UserClaim Info >

            //*get User from Token

            var userClaim_in_Token = HttpContext.User.Claims.Where(c => c.Type == ClaimsIdentity.DefaultNameClaimType).FirstOrDefault(); //User as Name

            if(userClaim_in_Token==null)

            {

                return null;

            }

            string sEmail = userClaim_in_Token.Value;

            //</ get UserClaim Info >

 

            //< check user >

            long IDCurrent_User = await Get_UserID(sEmail);

            //</ check user >

 

 

            //--< Get Linq.Query >--

            //*gets last 10 Projects with View_Sum

            var query = (from n in _dbContext.tbl_Projects

                         //where n.IDOwner == IDCurrent_User

                         orderby n.IDProject descending

                         select  n ).Take(10);

            //--</ Get Linq.Query >--

 

 

            //----< fill Data_to_View >----

            List<ProjectModel> dataList = query.ToList<ProjectModel>();

            

 

            //< out >

            //*output to client

            return dataList;

            //</ out >

            //-------------</ Index >------------- 

        }

 

 

 

        //HttpPost URL=/api/projects  

        //*Post=Create, Put=Update

        [HttpPost]

        public async Task<ActionResult> Create()

        {

            //-------------< Create() >------------- 

            //< get UserClaim Info >

            //*get User from Token

            var userClaim_in_Token = HttpContext.User.Claims.Where(c => c.Type == ClaimsIdentity.DefaultNameClaimType).FirstOrDefault(); //User as Name

            if (userClaim_in_Token == null)

            {

                return null;

            }

            string sEmail = userClaim_in_Token.Value;

            //</ get UserClaim Info >

 

            //< check user >

            long IDCurrent_User = await Get_UserID(sEmail);

            //</ check user >

 

            //--< Read UploadData >--

            StreamReader reader = new StreamReader(Request.Body);

            JObject jsonData = JObject.Parse(reader.ReadToEnd());

            string sTitle = jsonData.GetValue("title").ToString();

            string sURLRef = jsonData.GetValue("url").ToString();

            string sHTML = jsonData.GetValue("html").ToString();

            string sOrt = jsonData.GetValue("ort").ToString();

            string sBereiche = jsonData.GetValue("bereiche").ToString();

            string sGehalt = jsonData.GetValue("gehalt").ToString();

            string sArt = jsonData.GetValue("art").ToString();

            //--</ Read UploadData >--

 

            //< correct >

            string sText = Html_Methods.HTML_to_Text(sHTML);

            //</ correct >

 

 

            //< Create Data >

            ProjectModel project = new ProjectModel();

 

            project.IDOwner = IDCurrent_User;

            project.URLRef = sURLRef ;

            project.Title = sTitle;

            project.HTML = sHTML;

            project.Text = sText;

            project.Ort = sOrt;

            project.Bereiche = sBereiche;

            project.Gehalt = sGehalt;

            project.Art = sArt;

 

            project.DtCreated = DateTime.Now;

            //</ Create Data >

 

 

            //< add recordset >

            _dbContext.tbl_Projects.Add(project);      

            //</ add recordset >

 

            //< save sqlserver >

            await _dbContext.SaveChangesAsync(true);

            //</ save sqlserver >

 

            long newIDProject_on_Server = project.IDProject;

 

            ActionResult  response= Json(new { status = "OK", newIDProject_on_Server = newIDProject_on_Server });

 

 

            //< out >

            //*output to client

            return response;

            //</ out >

            //-------------</ Create() >------------- 

        }

 

        //HttpClient-URL: httpDelete /api/projects/5

        [HttpDelete("{id}")]

        public async TaskActionResult> Delete(int id)

        {

            //-------------< HttpDelete(ID) >------------- 

            //< get UserClaim Info >

            //*get User from Token

            var userClaim_in_Token = HttpContext.User.Claims.Where(c => c.Type == ClaimsIdentity.DefaultNameClaimType).FirstOrDefault(); //User as Name

            if (userClaim_in_Token == null)

            {

                return null;

            }

            string sEmail = userClaim_in_Token.Value;

            //</ get UserClaim Info >

 

            //< check user >

            long IDCurrent_User = await Get_UserID(sEmail);

            //</ check user >

 

 

            //< get_database >

            ProjectModel project = _dbContext.tbl_Projects.SingleOrDefault(n => n.IDProject == id);

            if (project == null) { return NotFound(); }

            //</ get_database >

 

            //< check Owner >

            long IDOwner = project.IDOwner;

            if (IDOwner != IDCurrent_User) { return BadRequest(); }

            //</ check Owner >

            

            //< Delete Note >

            _dbContext.tbl_Projects.Remove(project);      //set Flag

            //</ Delete Note >

 

            //< delete project+images >

            await _dbContext.SaveChangesAsync(true);

            //</ delete project+images >

 

            //< out >

            //*output to client

            return Ok();

            //</ out >

            //-------------</ HttpDelete(ID) >------------- 

        }

 

        private async Task<long> Get_UserID(string sEmail)

        {

            //------------< Check_User() >------------

            //*gets UserID as long from AspUsers by Email

            //< check >

            if (sEmail== null) { return 0; }

            if (sEmail == "") { return 0; }

            if (sEmail.IndexOf("@")<0) { return 0; }

            //</ check >

 

            //< get AspUser >

            var aspUser = _dbContext.Users.SingleOrDefault(u => u.Email == sEmail);

            if (aspUser ==null) { return 0; }

            //</ get AspUser >

 

            //< get tbl_User >

            UserModel User = await _dbContext.tbl_Users.SingleOrDefaultAsync(u => u.IDAspNetUser == aspUser.Id);

            //</ get tbl_User >

 

            //< out >

            return User.IDUser ; //as long

            //</ out >

            //------------</ Check_User() >------------

        }

 

        //--------------</ Class: ApiController  >---------------------

    }

}