c#中WepAPI(post/get)控制器方法创建和httpclient调用webAPI实例

本文主要是介绍c#中WepAPI(post/get)控制器方法创建和httpclient调用webAPI实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一:WebAPI创建

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    /// <summary>
    /// 控制器类
    /// </summary>
    public class UserInfoController: ApiController
    {
        //  /api/UserInfo/CheckUserName?_userName="admin"  

        //以上是webAPI路由配置,对应WebAPIConfig.cs类(App_Startw文件夹中)
        //其中api固定,可手动在WebAPIConfig里改,
        //UserInfo是控制器类(UserInfoController,简化成了UserInfo,框架中根据名称找到),
        //CheckUserName是get、post、put、delete等方法的名称,
        //_userName是形参名称

        //检查用户名是否已注册
        private ApiTools tool = new ApiTools();
        [HttpPost]
        public HttpResponseMessage CheckUserName1(object _userName)
        {
            int num = UserInfoGetCount(_userName.ToString());//查询是否存在该用户
            if (num > 0)
            {
                return tool.MsgFormat(ResponseCode.操作失败, "不可注册/用户已注册", "1 " + _userName);
            }
            else
            {
                return tool.MsgFormat(ResponseCode.成功, "可注册", "0 " + _userName);
            }
           // return new HttpResponseMessage { Content = new StringContent("bbb") }; ;//可直接返回字符串,
        }

        [HttpGet]
        public HttpResponseMessage CheckUserName(string _userName)
        {
            int num = UserInfoGetCount(_userName);//查询是否存在该用户
            if (num > 0)
            {
                return tool.MsgFormat(ResponseCode.操作失败, "不可注册/用户已注册", "1 " + _userName);
            }
            else
            {
                return new HttpResponseMessage { Content = new StringContent("aaa") }; ;//可直接返回字符串,
                return tool.MsgFormat(ResponseCode.成功, "可注册", "0 " + _userName);//也可返回json类型
            }
        }

        private int UserInfoGetCount(string username)
        {
            //return Convert.ToInt32(SearchValue("select count(id) from userinfo where username='" + username + "'"));
            return username == "admin" ? 1 : 0;
        }


    }
    /// <summary>
    /// 响应类
    /// </summary>
    public class ApiTools
    {
        private string msgModel = "{{\"code\":{0},\"message\":\"{1}\",\"result\":{2}}}";
        public ApiTools()
        {
        }
        public HttpResponseMessage MsgFormat(ResponseCode code, string explanation, string result)
        {
            string r = @"^(\-|\+)?\d+(\.\d+)?$";
            string json = string.Empty;
            if (Regex.IsMatch(result, r) || result.ToLower() == "true" || result.ToLower() == "false" || result == "[]" || result.Contains('{'))
            {
                json = string.Format(msgModel, (int)code, explanation, result);
            }
            else
            {
                if (result.Contains('"'))
                {
                    json = string.Format(msgModel, (int)code, explanation, result);
                }
                else
                {
                    json = string.Format(msgModel, (int)code, explanation, "\"" + result + "\"");
                }
            }
            return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
        }
       
    }
    /// <summary>
    /// 反馈码
    /// </summary>
    public enum ResponseCode
    {
        操作失败 = 00000,
        成功 = 10200,
    }

}

//

 // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

二:httpclient调用webAPI

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ConsoleTest
{
    public class ApiHelper
    {
        /// <summary>
        /// api调用方法/注意一下API地址
        /// </summary>
        /// <param name="controllerName">控制器名称--自己所需调用的控制器名称</param>
        /// <param name="overb">请求方式--get-post-delete-put</param>
        /// <param name="action">方法名称--如需一个Id(方法名/ID)(方法名/?ID)根据你的API灵活运用</param>
        /// <param name="obj">方法参数--如提交操作传整个对象</param>
        /// <returns>json字符串--可以反序列化成你想要的</returns>
        public static string GetApiMethod(string controllerName, string overb, string action, HttpContent obj )
        {
            Task<HttpResponseMessage> task = null;
            string json = "";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:51353/api/" + controllerName + "/");
            switch (overb)
            {
                case "get":
                    task = client.GetAsync(action);
                    break;
                case "post":
                    task = client.PostAsync(action, obj);
                    break;
                case "delete":
                    task = client.DeleteAsync(action);
                    break;
                case "put":
                    task = client.PutAsync(action, obj);
                    break;
                default:
                    break;
            }
            task.Wait();
            var response = task.Result;
            //MessageBox.Show(response.ToString());
            if (response.IsSuccessStatusCode)
            {
                var read = response.Content.ReadAsStringAsync();
                read.Wait();
                json = read.Result;
            }
            return json;
        }
      
        public static HttpContent GetContent( object model)
        {
            var body = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
            var content = new StringContent(body, Encoding.UTF8, "application/json");
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return content;
        }
    }
    public class A
    {
        public string Value = "999";
    }
}

//

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //  HttpContent httpContent = ApiHelper.GetContent(new A().Value);
                HttpContent httpContent = ApiHelper.GetContent("admin");
               string jsonStr= ApiHelper.GetApiMethod("UserInfo", "post", "CheckUserName1", httpContent);
               Console.WriteLine(jsonStr);
                Console.ReadKey();
            }
            catch(Exception ee)
            {
                MessageBox.Show(ee.ToString());
            }
            return;

这篇关于c#中WepAPI(post/get)控制器方法创建和httpclient调用webAPI实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1052244

相关文章

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

java向微信服务号发送消息的完整步骤实例

《java向微信服务号发送消息的完整步骤实例》:本文主要介绍java向微信服务号发送消息的相关资料,包括申请测试号获取appID/appsecret、关注公众号获取openID、配置消息模板及代码... 目录步骤1. 申请测试系统2. 公众号账号信息3. 关注测试号二维码4. 消息模板接口5. Java测试

在Golang中实现定时任务的几种高效方法

《在Golang中实现定时任务的几种高效方法》本文将详细介绍在Golang中实现定时任务的几种高效方法,包括time包中的Ticker和Timer、第三方库cron的使用,以及基于channel和go... 目录背景介绍目的和范围预期读者文档结构概述术语表核心概念与联系故事引入核心概念解释核心概念之间的关系

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

在Linux终端中统计非二进制文件行数的实现方法

《在Linux终端中统计非二进制文件行数的实现方法》在Linux系统中,有时需要统计非二进制文件(如CSV、TXT文件)的行数,而不希望手动打开文件进行查看,例如,在处理大型日志文件、数据文件时,了解... 目录在linux终端中统计非二进制文件的行数技术背景实现步骤1. 使用wc命令2. 使用grep命令