Projekt-Anfragen: Tel: 07022/9319004 info@CodeDocu.de Software Entwicklung in C# WPF Asp.Net Core Vba Excel Word SQL-Server EF Linq, UWP Net
#

WPF: Web API Lesen

 

Dieses Beispiel zeigt, wie man in WPF die Werte von einem Web-Server mit API lesen kann.

 

Auf dem Server ist ASP.Net Core Web API installiert.  (IIS Express Server mit SQL Server Express local DB)

Als Desktop Program ist ein WPF Anwendung installiert.

 

Auf dem WPF Anwendung erstellt man ein Window und in diesem holt man die Daten mit einem HttpClient und einem Webrequest ab.

HttpResponseMessage response und HttpClient client

Als Daten werden in diesem Fall Daten nach dem Datenmodel Project erzeugt.

static async Task<Project> GetAPIAsync(string path)

        {

            Project project = null;

            HttpResponseMessage response = await client.GetAsync(path);

            if (response.IsSuccessStatusCode)

            {

                project = await response.Content.ReadAsAsync<Project>();

            }

            return project;

        }

 

 

Daten Struktur, Model.

public class Project

{

  //-------------< Class: Model_Project >-------------

  public int ID_Project { get; set; }

  public string URL { get; set; }

  public string Title { get; set; }

  public string Text { get; set; }

  //-------------</ Class: Model_Project >-------------

}

 

Der Aufruf erfolgt, in dem man die Daten unter der Web API Adresse https://localhost:44356/api/Projects/1 herunterliest.

 

Dadurch wird im Beispiel der Datensatz gelesen

API Result on /api/Projects/1:

Title=title 14:26

Text=text 1

URL=http://microsoft.de/changed

 

Completter C# Code zum Lesen eines Datensatzes

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

 

namespace WebRobot_ComputerFutures

{

    /// <summary>

    /// Interaction logic for ApiWindow.xaml

    /// </summary>

    public partial class ApiWindow : Window

    {

        static HttpClient client = new HttpClient();

 

        public ApiWindow()

        {

            InitializeComponent();

        }

 

        private async void btnApi_Click(object sender, RoutedEventArgs e)

        {

            Project project = await GetAPIAsync("https://localhost:44356/api/Projects/1");

            //Console.WriteLine("Project1 " + project.Title);

 

            String sResult = "API Result on /api/Projects/1: " + Environment.NewLine + "Title=" + project.Title + Environment.NewLine + "Text=" + project.Text;

            sResult += Environment.NewLine + "URL=" + project.URL ;

            //MessageBox.Show(sResult, "API Read");

            tbxApi.Text = sResult;

        }

 

        public class Project

        {

 

            //-------------< Class: Model_Project >-------------

            public int ID_Project { get; set; }

            public string URL { get; set; }

            public string Title { get; set; }

            public string Text { get; set; }

 

            //public DateTime? DtList { get; set; }

            //public DateTime? DtScan { get; set; }

            //public DateTime? DtEdit { get; set; }

            //public DateTime? DtCreated { get; set; }

            //-------------</ Class: Model_Project >-------------

        }

 

 

        static async Task<Project> GetAPIAsync(string path)

        {

            Project project = null;

            HttpResponseMessage response = await client.GetAsync(path);

            if (response.IsSuccessStatusCode)

            {

                project = await response.Content.ReadAsAsync<Project>();

            }

            return project;

        }

    }

}

 

 

WPF und Asp.Net Core API

 

Auf dem Webserver sind daten in der Json Struktur vorhanden. Eingebettet ist hier ein Datensatz mit dem MVC Daten-Model Project

{"iD_Project":1,"url":"http://microsoft.de/changed","title":"title 14:26","text":"text 1","dtList":null,"dtScan":null,"dtEdit":"2018-01-10T14:30:59","dtCreated":null}

         

 

ASP.Net Core API

Zum Bereitstellen der Daten wurde unter Asp.Net Core ein Unterverzeichnis /Api erstellt und dann mit Create Scaffolded Item der ApiController erstellt

 

 

Video Tutorial

 

 

 

C# Code des API Controllers

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Freiberufler.Data;

using Freiberufler.Models;

 

namespace Freiberufler.Controllers.Api

{

    [Produces("application/json")]

    [Route("api/Projects")]

    public class ProjectsController : Controller

    {

        private readonly ApplicationDbContext _context;

 

        public ProjectsController(ApplicationDbContext context)

        {

            _context = context;

        }

 

        // GET: api/Projects

        [HttpGet]

        public IEnumerable<Project> Gettbl_Projects()

        {

            return _context.tbl_Projects;

        }

 

        // GET: api/Projects/1

        [HttpGet("{id}")]

        public async Task<IActionResult> GetProject([FromRoute] int id)

        {

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            var project = await _context.tbl_Projects.SingleOrDefaultAsync(m => m.ID_Project == id);

 

            if (project == null)

            {

                return NotFound();

            }

 

            return Ok(project);

        }

 

        // PUT: api/Projects/5

        [HttpPut("{id}")]

        public async Task<IActionResult> PutProject([FromRoute] int id, [FromBody] Project project)

        {

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            if (id != project.ID_Project)

            {

                return BadRequest();

            }

 

            _context.Entry(project).State = EntityState.Modified;

 

            try

            {

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateConcurrencyException)

            {

                if (!ProjectExists(id))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }

 

            return NoContent();

        }

 

        // POST: api/Projects

        [HttpPost]

        public async Task<IActionResult> PostProject([FromBody] Project project)

        {

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            _context.tbl_Projects.Add(project);

            await _context.SaveChangesAsync();

 

            return CreatedAtAction("GetProject", new { id = project.ID_Project }, project);

        }

 

        // DELETE: api/Projects/5

        [HttpDelete("{id}")]

        public async Task<IActionResult> DeleteProject([FromRoute] int id)

        {

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            var project = await _context.tbl_Projects.SingleOrDefaultAsync(m => m.ID_Project == id);

            if (project == null)

            {

                return NotFound();

            }

 

            _context.tbl_Projects.Remove(project);

            await _context.SaveChangesAsync();

 

            return Ok(project);

        }

 

        private bool ProjectExists(int id)

        {

            return _context.tbl_Projects.Any(e => e.ID_Project == id);

        }

    }

}

 

Mobile
API
»
Json Fehler: Eine Methode wurde zu einem unerwarteten Zeitpunkt aufgerufen
»
StatusCode: 405, ReasonPhrase: Method Not Allowed
»
Asp.Net Core: Ajax Web Api Code Beispiel
»
WPF: Web API Lesen von Asp Net Api mit HttpClient
»
API: Daten Ändern und Erstellen mit Api Beispiel Code
»
Problem ASP.Net: ID wird um 1000 erhöht

.

Jobs, Projekte, Angebote für Freiberufler, Selbstständig an Info@CodeDocu.de