博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#中WepAPI(post/get)控制器方法创建和httpclient调用webAPI实例
阅读量:4303 次
发布时间:2019-05-27

本文共 5174 字,大约阅读时间需要 17 分钟。

一: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;

转载地址:http://pnlws.baihongyu.com/

你可能感兴趣的文章
期货市场技术分析07_摆动指数和相反意见理论
查看>>
满屏的指标?删了吧,手把手教你裸 K 交易!
查看>>
不吹不黑 | 聊聊为什么要用99%精度的数据回测
查看>>
X 分钟速成 Python
查看>>
对于模拟交易所引发的思考
查看>>
高频交易的几种策略
查看>>
量化策略回测TRIXKDJ
查看>>
量化策略回测唐安奇通道
查看>>
CTA策略如何过滤部分震荡行情?
查看>>
量化策略回测DualThrust
查看>>
量化策略回测BoolC
查看>>
量化策略回测DCCV2
查看>>
mongodb查询优化
查看>>
五步git操作搞定Github中fork的项目与原作者同步
查看>>
git 删除远程分支
查看>>
删远端分支报错remote refs do not exist或git: refusing to delete the current branch解决方法
查看>>
python multiprocessing遇到Can’t pickle instancemethod问题
查看>>
APP真机测试及发布
查看>>
通知机制 (Notifications)
查看>>
10 Things You Need To Know About Cocoa Auto Layout
查看>>