调用接口一般采用两种方式,webservice和webapi,此篇写webapi建立及测试
1.创建:
2.添加控制器到Controller文件夹,新建Api文件夹,将该控制器文件放入Api下,打开App_Start文件夹下webapiconfig,修改路由,
public static void Register(HttpConfiguration config) { config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
3.方法名定义注意点
a.如果方法名为post或者get,就是默认使用,在测试时,直接写到控制器LQInfo,然后传递方式设置为post即可,不需要写方法;
b.如果自定义方法,选择方式为get或者post,那么需要写到具体方法getcode();
在用 winform调用测试时,也需要写到方法:
private void button1_Click(object sender, EventArgs e) { string ashxSite = "http://localhost:80//ActionApi"; var client = new RestClient(ashxSite); var request = new RestRequest("/UserInfo/GetCode", Method.GET); request.AddParameter("Barcode", "WLS000021"); var response = client.Execute(request); // 从 WebAPI 获取 textBox2.Text = response.Content; }
4.参数注意点
a.如果参数只为一个:
[HttpPost] public string GetCode(string Barcode) { try { using (OracleConnection conn = new OracleConnection(connERP)) { string sql = @"select trim(a.t$mitm ) 编码,trim(b.t$dsca) 名称 from tablea a join tableb b on trim(a.t$pdno)=:a and a.t$mitm = b.t$item"; Object obj = conn.QueryFirstOrDefault(sql, new { a = Barcode }); if (obj != null) { string item = obj.ToString(); return item; } else return null; } } catch (Exception ex) { return "Error." + ex.Message; } }
b.从URL获取参数值的方式的弊端是URL有长度限制,当超过浏览器的最大URL长度时请求将被浏览器拒绝,根本不会发出去。
因此,当参数值过大时需要用[FromBody]参数进行传输
public class AX { public string url { get; set; } } public string Post([FromBody] AX arg ) { // 传入的字符串:"action=search&arg1=" + user + "&arg2=" + ED_tiaoMa.getText().toString(); // 先用&分割,再用=分割 string ip = HttpContext.Current.Request.UserHostAddress; if (arg!= null && !string.IsNullOrEmpty(arg.url)) { log.DebugFormat("Post:{0}", arg.url); var tmps = arg.url.Split(‘&‘); string action = string.Empty; string arg1 = string.Empty; string arg2 = string.Empty; string arg3 = string.Empty; string arg4 = string.Empty; foreach (var item in tmps) { var tmps2 = item.Split(‘=‘); var s = tmps2[0].Trim().ToLower(); //第一个参数 方法 var _value = tmps2[tmps2.Length - 1].Trim(); //最后一个参数 if (tmps2.Length < 2) _value = string.Empty; if ("action".Equals(s, StringComparison.OrdinalIgnoreCase)) action = _value; else if ("arg1".Equals(s, StringComparison.OrdinalIgnoreCase)) arg1 = _value; else if ("arg2".Equals(s, StringComparison.OrdinalIgnoreCase)) arg2 = _value; else if ("arg3".Equals(s, StringComparison.OrdinalIgnoreCase)) arg3 = _value; else if ("arg4".Equals(s, StringComparison.OrdinalIgnoreCase)) arg4 = _value; } log.DebugFormat("Post: {0} / {1} / {2} / {3} / {4} / {5}", action, arg1, arg2, arg3, arg4, ip); if (string.IsNullOrWhiteSpace(action)) return "不支持此方法!"; var a1 = action.Trim().ToLower(); switch (a1) { case "getcode": { try { using (OracleConnection conn = new OracleConnection(connErp)) { string sql = @"select trim(a.t$mitm ) 编码,trim(b.t$dsca) 名称 from tablea a join tableb b on trim(a.t$pdno)=:a and a.t$mitm = b.t$item"; Object obj = conn.QueryFirstOrDefault(sql, new { a = arg1 }); if (obj != null) { string item = obj.ToString(); return item; } else return null; } } catch (Exception ex) { return "Error." + ex.Message; } } return action; } } return "Error." + arg.url; }