C# 搭建一個簡單的WebApi項目
WebApi相關文章:
- C# 搭建一個簡單的Web API項目
- C# WebApi 路由配置
- c# WebApi之解決跨域問題:Cors
- c# WebApi之身份驗證:Basic基礎認證
- c# WebApi之接口返回類型詳解
一、創建Web API
1、創建一個新的web API項目
啟動VS 2013,並在“開始頁”選擇“新項目”。或從“文件”菜單選擇“新建”,然后選擇“項目”。
在“模板”面板中選擇“已安裝模板”,並展開“Visual C#”節點。選擇該節點下的“Web”。在項目模板列表中選擇“ASP.NET MVC 4 Web應用程序”。
在“新的ASP.NET MVC 4項目”對話框中選擇“Web API”
二、Web API路由配置
1、創建好項目后,文件目錄如下:
2、打開App_Start文件夾下的 WebApiConfig.cs 文件
默認路由配置信息為:
WebApi的默認路由是通過http的方法(get/post/put/delete)去匹配對應的action,也就是說webapi的默認路由並不需要指定action的名稱。
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我們自定義一個路由配置:
//自定義路由:匹配到action
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "actionapi/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
url: "{controller}/{action}/{id}"這個定義了我們url的規則,{controller}/{action}定義了路由的必須參數,{id}是可選參數
三、創建Web API方法
1、在Controllers文件夾下新建一個控制器類,添加一個post請求
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;
}
}
2、添加返回(響應)類
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,
}
- 1
- 2
- 3
- 4
- 5
四、調用Web API接口
1、給大家推薦一款比較好用的接口測試軟件:
https://www.getpostman.com
2、如果想測試上面寫的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}參數
u