winForm调用WebApi程序

Posted a-r-e-s

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winForm调用WebApi程序相关的知识,希望对你有一定的参考价值。

WinForm窗体创建的调用api的类
/// <summary> /// 调用api返回json /// </summary> /// <param name="url">api地址</param> /// <param name="jsonstr">接收参数</param> /// <param name="type">类型</param> /// <returns></returns> public static string HttpPost(string url, string jsonstr)//,string type HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //--需要封装的参数 request.CookieContainer = new CookieContainer(); //以下是发送的http头 request.Referer = ""; //request.ContentType = "text/xml"; request.Headers["Accept-Language"] = "zh-CN,zh;q=0."; request.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3"; request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (Khtml, like Gecko) Chrome/14.0.835.202 Safari/535.1"; request.KeepAlive = true; //上面的http头看情况而定,但是下面俩必须加 request.ContentType = "application/x-www-form-urlencoded"; Encoding encoding = Encoding.UTF8;//根据网站的编码自定义 request.Method = "get"; //--需要将get改为post才可行 string postDataStr; //Stream requestStream = request.GetRequestStream(); if (jsonstr != "") postDataStr = jsonstr;//--需要封装,形式如“arg=arg1&arg2=arg2” byte[] postData = encoding.GetBytes(postDataStr);//postDataStr即为发送的数据, //request.ContentLength = postData.Length; //写入后不允许设置此属性 //requestStream.Write(postData, 0, postData.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //远程服务器返回错误: (405) 不允许的方法/远程服务器返回错误: (500) 内部服务器错误。 Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, encoding); string retString = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); return retString;

 API程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace webApi_test2.Models

   //方法接口
    public interface IUsersRepository
    
        Task<Users> GetUser(string id);
        Task<int> DeleteUser(string ID);
        Task<int> AddAUsers(Users item);
        Task<int> UpdateUsers(Users item);
    

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace webApi_test2.Models

    //实体类
    public class Users
    
        public string UserID  get; set; 
        public string Pwd  get; set; 
        public string UserName  get; set; 
        public string Remark  get; set; 
        public DateTime CreatedOn  get; set; 
        public DateTime LastLoginTime  get; set; 
    

 

using Ivony.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace webApi_test2.Models

    //接口的实现 (接口的实现方法根据框架的结构自行修改)
    public class UsersRepository : IUsersRepository
    
        //查询
        public async Task<Users> GetUser(string id)
        
            using (Db.UseDatabase("default"))
            
                var x = Db.T($"select * from Users where UserID=id").ExecuteEntityAsync<Users>();
                return await x;
            
        
        //删除
        public async Task<int> DeleteUser(string ID)
        
            using (Db.UseDatabase("default"))
            
                return await Db.T($"delete from Users where UserID=ID").ExecuteNonQueryAsync();
            
        
        //添加
        public async Task<int> AddAUsers(Users UsersItem)
        
            using (Db.UseDatabase("default"))
            
                return await Db.T($"insert into Users(UserID,Pwd,UserName,CreatedOn) values(UsersItem.UserID,UsersItem.Pwd,UsersItem.UserName,UsersItem.CreatedOn)").ExecuteNonQueryAsync();
            
        
        //修改
        public async Task<int> UpdateUsers(Users UserItem)
        
            using (Db.UseDatabase("default"))
            
                return await Db.T($"update Users set Pwd=UserItem.Pwd,UserName=UserItem.UserName,CreatedOn=UserItem.CreatedOn where UserID=UserItem.UserID").ExecuteNonQueryAsync();
            
        
    

 创建Api控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Ivony.Data;
using Microsoft.AspNetCore.Mvc;
using webApi_test2.Models;


namespace webApi_test2.Controllers

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    
        //接口的依赖注入根据自己框架的要求进行注入  本框架使用自己的源,与其他稍有不同
        private IUsersRepository _Repository  get; set; 
        public ValuesController(IUsersRepository Repository)
        
            _Repository = Repository;
        

        //GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        
            return new string[]  "value1", "value2" ;
        

        // GET api/values/5
        [HttpGet("id")]
        public ActionResult<string> Get(int id)
        
            return "value";
        

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        
        
        // PUT api/values/5
        [HttpPut("id")]
        public void Put(int id, [FromBody] string value)
        
        
        //删除
        // DELETE api/values/5
        [HttpGet("Delete")]
        public int Delete(string id)
        
            try
            
                //UsersRepository ur = new UsersRepository();
                //var x = ur.DeleteUser(id);

                var x = _Repository.DeleteUser(id);
               
                return x.Result;
            
            catch(Exception ex)
            
                throw;
            
          
        
        //修改
        [HttpGet("UpdateUsers")]
        public async Task<int> UpdateUsers(string UserID, string UserName, string Pwd, string CreatedOn)/*Users UserItem*/
        
            Users UserItem = new Users();
            try
            
                //初始化赋值
                UserItem.UserID = UserID;
                UserItem.Pwd = Pwd;
                UserItem.UserName = UserName;
                UserItem.CreatedOn = Convert.ToDateTime(CreatedOn);
                
                //UsersRepository ur = new UsersRepository();
                //var x = ur.UpdateUsers(UserItem);

                var x = _Repository.UpdateUsers(UserItem);
                return await x;
            
            catch (Exception)
            
                throw;
            
        
        //查询 根据UserID查询
        [HttpGet("GetUser")]
        public async Task<Users> GetUser(string UserID)
        
            try
            
                //UsersRepository ur = new UsersRepository();
                //var x = ur.GetUser(UserID);

                var x = _Repository.GetUser(UserID);
                return await x;

                //return await _Repository.GetUser(UserID);
            
            catch (Exception)
            
                throw;
            
        
        //添加
        //GET:/api/values/Get
        [HttpGet("AddUsers")]
        public async Task<int> AddUsers(string UserID, string UserName, string Pwd, string CreatedOn)/*Users Item*/
        
            Users UserItem = new Users();
            try
            
                UserItem.UserID = UserID;
                UserItem.Pwd = Pwd;
                UserItem.UserName = UserName;
                UserItem.CreatedOn = Convert.ToDateTime(CreatedOn);
                //UsersRepository ur = new UsersRepository();
                //var x = ur.AddAUsers(UserItem);
                var x = _Repository.AddAUsers(UserItem);
                return await x;
            
            catch (Exception)
            
                throw;
            
        
    

 依赖注入需要的类

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nebula.Hosting;
using webApi_test2.Models;

[assembly: HostInitialize(typeof(webApi_test2.Models.ServiceInitialize))]//webApi_test2.Models.ServiceInitialize 文件位置
namespace webApi_test2.Models

    internal class ServiceInitialize
    
        public static void Initialize(IServiceCollection services)
        
            services.AddSingleton<IUsersRepository, UsersRepository>();
        
    

 WinForm调用api程序方法来源于

https://www.cnblogs.com/mq0036/p/10437993.html

 

仅此,以作记录。

 

 

 

 

以上是关于winForm调用WebApi程序的主要内容,如果未能解决你的问题,请参考以下文章

winforms应用添加双向web api的解决方案

C# winform 如何引用webservices

有关C#winform的调用外部程序的问题

在.net下,如何用winform去访问web服务器

C#winform 关于调用外部程序的问题

C# winform程序调用第三方动态库出现问题