本文主要是介绍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实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!