c#中WepAPI(post/get)控制器方法创建和httpclient调用webAPI实例
一:WebAPI創(chuàng)建
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路由配置,對(duì)應(yīng)WebAPIConfig.cs類(App_Startw文件夾中)
? ? ? ? //其中api固定,可手動(dòng)在WebAPIConfig里改,
? ? ? ? //UserInfo是控制器類(UserInfoController,簡(jiǎn)化成了UserInfo,框架中根據(jù)名稱找到),
? ? ? ? //CheckUserName是get、post、put、delete等方法的名稱,
? ? ? ? //_userName是形參名稱
? ? ? ? //檢查用戶名是否已注冊(cè)
? ? ? ? private ApiTools tool = new ApiTools();
? ? ? ? [HttpPost]
? ? ? ? public HttpResponseMessage CheckUserName1(object _userName)
? ? ? ? {
? ? ? ? ? ? int num = UserInfoGetCount(_userName.ToString());//查詢是否存在該用戶
? ? ? ? ? ? if (num > 0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return tool.MsgFormat(ResponseCode.操作失敗, "不可注冊(cè)/用戶已注冊(cè)", "1 " + _userName);
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return tool.MsgFormat(ResponseCode.成功, "可注冊(cè)", "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.操作失敗, "不可注冊(cè)/用戶已注冊(cè)", "1 " + _userName);
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return new HttpResponseMessage { Content = new StringContent("aaa") }; ;//可直接返回字符串,
? ? ? ? ? ? ? ? return tool.MsgFormat(ResponseCode.成功, "可注冊(cè)", "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>
? ? /// 響應(yīng)類
? ? /// </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調(diào)用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調(diào)用方法/注意一下API地址
? ? ? ? /// </summary>
? ? ? ? /// <param name="controllerName">控制器名稱--自己所需調(diào)用的控制器名稱</param>
? ? ? ? /// <param name="overb">請(qǐng)求方式--get-post-delete-put</param>
? ? ? ? /// <param name="action">方法名稱--如需一個(gè)Id(方法名/ID)(方法名/?ID)根據(jù)你的API靈活運(yùn)用</param>
? ? ? ? /// <param name="obj">方法參數(shù)--如提交操作傳整個(gè)對(duì)象</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;
總結(jié)
以上是生活随笔為你收集整理的c#中WepAPI(post/get)控制器方法创建和httpclient调用webAPI实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Linux 下清空或删除大文件内容的 5
- 下一篇: c# char unsigned_dll