一、前言
工作也有一年多了,从进入公司就一直进行BIM(建筑信息模型)C/S产品的研发,平时写的最多的就是Dev WPF。一个偶然的时机,产品需要做支付宝扫码与微信扫码,所以需要了解产品服务器中的授权服务是如何编写的,以此开始接触Web。本篇将以小白的视角学习Webapi,老司机可以直接略过。
二、Webapi编写
Step1: 编写WebApiConfig.cs,这个不用多说,就是设置路由嘛。
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
Step2: 在Global.asax文件中初始化路由映射。
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); } }
Step3: 创建controller,编写Api具体服务。
public class TestController: ApiController { [HttpGet]
public string ConnectionTest()
{
return "connected_success";
}
[HttpPost]
public HttpResponseMessage GetInfo(string value1, string value2)
{
var info = new Info()
{
Property1 = value1,
Property2 = value2,
Property3 = "3"
};
HttpResponseMessage response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject(info), Encoding.GetEncoding("UTF-8"),"application/json")
};
return response;
} }
这样,一个简单的实例就编写好了。根据之前的路由映射规则:"api/{controller}/{action}/{id}",我们的访问地址就是:http://xxx.xxx.com:xxx/api/Test/GetName
三、Webapi的请求
api写完了,总要去请求这个api服务的吧,那么我们得首先明白HttpGet与HttpPost两种请求方式的区别。从字面上来说,Get是获取,Post是投递、推送的意思。结合其它资料我觉得以下解释还是比较容易理解的:
下面就是两种请求方式的写法,包括前台与后台的写法。前台以ajax,后台就是C#。
Method1: Get请求写法
前台Get请求写法:
//无参数 $.ajax({ url: "/api/controllerName/ActionName type: "GET", success: function (data) { // } }) //带参数 $.ajax({ url: "/api/controllerName/ActionName type: "GET", data:{"property1":value1,"property2":value2}, success: function (data) { // } }) 或者 $.ajax({ url: "/api/controllerName/ActionName/?property1="+value1+"&property2="+value2, type: "GET", success: function (data) { // } })
后台Get请求写法:
public static void TestGet(string serverAddress) { try { HttpClient httpsClient = new HttpClient { BaseAddress = new Uri(serverAddress), Timeout = TimeSpan.FromMinutes(20) }; if (DsClientOperation.ConnectionTest(httpsClient)) //这里是连接测试判断,可根据业务自行调整 { stringGetUrl = httpsClient.BaseAddress + "api/ControllerName/ActionName"; //若带参,参数写在url里,例:xxx.com?order=参数1 Uri address = new Uri(PostUrl); Task<HttpResponseMessage> response = httpsClient.GetAsync(address); response.ContinueWith( (getTask) => { if (getTask.IsFaulted) { throw getTask.Exception; } HttpResponseMessage getResponse = getTask.Result; getResponse.EnsureSuccessStatusCode(); var result = getResponse.Content.ReadAsStringAsync().Result; return result; }); } } catch { } }
public static bool ConnectionTest(string serverAddress) { if (string.IsNullOrEmpty(serverAddress)) return false; HttpClient httpClient = new HttpClient { BaseAddress = new Uri(serverAddress), Timeout = TimeSpan.FromSeconds(30) }; Uri address = new Uri(httpClient.BaseAddress + "api/Test/ConnectionTest"); Task<HttpResponseMessage> task = httpClient.GetAsync(address); try { task.Wait(); } catch { return false; } HttpResponseMessage response = task.Result; if (!response.IsSuccessStatusCode) return false; string connectionResult; try { var result = response.Content.ReadAsStringAsync().Result; connectionResult = JsonConvert.DeserializeObject<string>(result); } catch { return false; } return connectionResult.Equals("connected_success"); }
Method2: Post请求写法
前台Post请求写法:
//无参数 $.ajax({ url: "api/ControllerName/ActionName", type: "Post", success: function (data) { } }); //有1个参数
$.ajax({
url: "api/ControllerName/ActionName",
type: "Post", dataType: "json",
contentType: "application/json",
data:{"":value1},
success: function (data) { } });
//有2个参数 $.ajax({ url: "api/ControllerName/ActionName", type: "Post", dataType: "json",
contentType: "application/json",
data:JSON.stringify({"property1":value1,"property2":value2}), success: function (data) { } });
//再多的话要封装成对象进行传输了
最重要的是Action里的参数有[FromBody]标签,并且FromBody只能写一次
[HttpPost]
public HttpResponseMessage Action([FromBody]dynamic yourparameter)
[HttpPost]
public HttpResponseMessage Action([FromBody]JObject yourparameter)
后台Post请求写法:
public static void TestPost(string productName, string serverAddress) { var productName = "Your Product"; var requestCode = "Your Number"; var clientDictionary = new Dictionary<string, string> { {"ProductName", productName}, {"RequestCode", requestCode}, }; var packageInfo = JsonConvert.SerializeObject(clientDictionary); if (!string.IsNullOrEmpty(packageInfo)) { try { HttpClient httpsClient = new HttpClient { BaseAddress = new Uri(serverAddress), Timeout = TimeSpan.FromMinutes(20) }; if (DsClientOperation.ConnectionTest(httpsClient)) //这里是连接测试判断,可根据业务自行调整 { StringContent strData = new StringContent( packageInfo, Encoding.UTF8, "application/json"); string PostUrl = httpsClient.BaseAddress + "api/ControllerName/ActionName"; Uri address = new Uri(PostUrl); Task<HttpResponseMessage> response = httpsClient.PostAsync(address, strData); response.ContinueWith( (postTask) => { if (postTask.IsFaulted) { throw postTask.Exception; } HttpResponseMessage postResponse = postTask.Result; postResponse.EnsureSuccessStatusCode(); var result = postResponse.Content.ReadAsStringAsync().Result;
return result; }); } } catch { } } }
四、结尾
大致就写到这里,如果有写错的地方可以在评论区留言,下一篇玩玩其它的,继续以小白视角研究研究MVC。