建立Web API

1、建立Web API
一、建立一個新的web API項目web

啓動VS 2013,並在「開始頁」選擇「新項目」。或從「文件」菜單選擇「新建」,而後選擇「項目」。json

在「模板」面板中選擇「已安裝模板」,並展開「Visual C#」節點。選擇該節點下的「Web」。在項目模板列表中選擇「ASP.NET MVC 4 Web應用程序」。api

 

在「新的ASP.NET MVC 4項目」對話框中選擇「Web API」app

 

 

 


2、Web API路由配置
一、建立好項目後,文件目錄以下:post

 


二、打開App_Start文件夾下的 WebApiConfig.cs 文件
默認路由配置信息爲:
WebApi的默認路由是經過http的方法(get/post/put/delete)去匹配對應的action,也就是說webapi的默認路由並不須要指定action的名稱。測試

// Web API 路由
config.MapHttpAttributeRoutes();url

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

咱們自定義一個路由配置:code

//自定義路由:匹配到action
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "actionapi/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

url: "{controller}/{action}/{id}"這個定義了咱們url的規則,{controller}/{action}定義了路由的必須參數,{id}是可選參數orm

3、建立Web API方法
一、在Controllers文件夾下新建一個控制器類,添加一個post請求blog

public class UserInfoController : ApiController
{
//檢查用戶名是否已註冊
private ApiTools tool = new ApiTools();
[HttpPost]
public HttpResponseMessage CheckUserName(string _userName )
{
int num = UserInfoGetCount(_userName);//查詢是否存在該用戶
if (num > 0)
{
return tool.MsgFormat(ResponseCode.操做失敗, "不可註冊/用戶已註冊", "1 " + userName);
}
else
{
return tool.MsgFormat(ResponseCode.成功, "可註冊", "0 " + userName);
}
}

private int UserInfoGetCount(string username)
{
//return Convert.ToInt32(SearchValue("select count(id) from userinfo where username='" + username + "'"));
return username == "admin" ? 1 : 0;
}
}

二、添加返回(響應)類

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") };
}
}

ResponseCode:

public enum ResponseCode
{
操做失敗 = 00000,
成功 = 10200,
}

4、調用Web API接口
一、給你們推薦一款比較好用的接口測試軟件:
https://www.getpostman.com

 


二、若是想測試上面寫的post方法,啓動Web Api項目後,在postman地址欄輸入:http://localhost:26753/ActionApi/UserInfo/CheckUserName,添加參數 userName=張三
結果以下:

 


還記得咱們以前自定義的路由信息嗎

config.Routes.MapHttpRoute( name: "ActionApi", routeTemplate: "actionapi/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });地址欄中的UserInfo 對應路由配置**{controller}參數CheckUserName 對應路由配置{action}參數userName=張三 對應 路由配置{id}**參數

相關文章
相關標籤/搜索