C#?webApi創(chuàng)建與發(fā)布、部署、api調用詳細教程
一.創(chuàng)建web api項目
1.1、項目創(chuàng)建
MVC架構的話,它會有view-model-control三層,在web api中它的前端和后端是分離的,所以只在項目中存在model-control兩層
1.2、修改路由
打開App_Start文件夾下,WebApiConfig.cs ,修改路由,加上{action}/ ,這樣就可以在api接口中通過接口函數(shù)名,來導向我們希望調用的api函數(shù),否則,只能通過controller來導向,就可能會造成有相同參數(shù)的不同名函數(shù),沖突。其中,{id}是api接口函數(shù)中的參數(shù)。
默認路由配置信息為:【默認路由模板無法滿足針對一種資源一種請求方式的多種操作?!?br />WebApi的默認路由是通過http的方法(get/post/put/delete)去匹配對應的action,也就是說webapi的默認路由并不需要指定action的名稱
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace WebAPI { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服務 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", //修改路由,加上{action}/ ,這樣就可以在api接口中通過接口函數(shù)名,來導向我們希望調用的api函數(shù), //否則,只能通過controller來導向,就可能會造成有相同參數(shù)的不同名函數(shù),沖突。其中,{id}是api接口函數(shù)中的參數(shù) routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
二.測試案例
寫一個測試的api函數(shù),并開始執(zhí)行(不調試)
2.1、我們在model文件夾中添加一個類movie
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAPI.Models { public class movie { public string name { get; set; } public string director { get; set; } public string actor { get; set; } public string type { get; set; } public int price { get; set; } } }
2.1.2、我們在model文件夾中添加一個類Product
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAPI.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }
2.2、在controller文件夾下添加web api控制器,命名改為TestController
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebAPI.Models; namespace WebAPI.Controllers { public class TestController : ApiController { movie[] mymovie = new movie[] { new movie { name="海蒂和爺爺",director="阿蘭.葛斯彭納",actor="阿努克",type="動漫",price=28}, new movie { name="云南蟲谷",director="佚名",actor="潘粵明",type="驚悚",price=32}, new movie { name="沙海",director="佚名",actor="吳磊",type="驚悚",price=28}, new movie { name="千與千尋",director="宮崎駿",actor="千尋",type="動漫",price=28} }; public IEnumerable<movie> GetAllMovies() { return mymovie; } public IHttpActionResult GetMovie(string name) //異步方式創(chuàng)建有什么作用 { var mov = mymovie.FirstOrDefault((p) => p.name == name); if (mymovie == null) { return NotFound(); } return Ok(mymovie); } } }
這樣就完成了一個web api實例的編寫
2.2.2、在controller文件夾下添加web api控制器,命名改為productsController
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebAPI.Models; namespace WebAPI.Controllers { public class productsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerable<Product> GetAllProducts() { return products; } public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } } }
2.2.3、在controller文件夾下添加web api控制器,命名改為MyController
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace WebAPI.Controllers { public class MyController : ApiController { [HttpGet] public string MyExample(string param1, int param2) { string res = ""; res = param1 + param2.ToString(); //這邊可以進行任意操作,比如數(shù)據(jù)存入或者取出數(shù)據(jù)庫等 return res; } } }
三.本地調試
3.1 運行調試,以本地 localhost(或127.0.0.1)形式訪問
①點擊工具欄【IIS Express】
②瀏覽地址輸入接口,看是否可以訪問
localhost:44381/api/products/GetAllProducts
注意:
這里的路徑是寫你的控制器前綴名稱(Control文件下的productsController控制器文件的前綴)
https://localhost:44381/api/Test/GetAllMovies
2)直接在瀏覽器中調試也行
想要調試的值,可以將WebApiConfig.cs的代碼修如下
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace WebAPI { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服務 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", //修改路由,加上{action}/ ,這樣就可以在api接口中通過接口函數(shù)名,來導向我們希望調用的api函數(shù), //否則,只能通過controller來導向,就可能會造成有相同參數(shù)的不同名函數(shù),沖突。其中,{id}是api接口函數(shù)中的參數(shù) routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); //去掉xml返回格式、設置json字段命名采用 var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); } } }
ok,顯示成功
localhost:44381/api/My/MyExample?param1=¶m2=2
WebApi項目實例3-1
3-1 (1)新添加到控制器UserInfoController,
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebAPI.Models; namespace WebAPI.Controllers { public class UserInfoController : ApiController { //檢查用戶名是否已注冊 private ApiTools tool = new ApiTools(); // [HttpPost] [HttpGet] 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; } } }
添加返回(響應)類ApiTools
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Web; namespace WebAPI.Models { //添加返回(響應)類 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") }; } } public enum ResponseCode { 操作失敗 = 00000, 成功 = 10200, } }
3-1 (2)本地調試,調用Web API接口
運行調試,以本地 localhost(或127.0.0.1)形式訪問
①點擊工具欄【IIS Express】
②瀏覽地址輸入接口,看是否可以訪問
https://localhost:44381/api/UserInfo/CheckUserName?_userName=wxd
3.2 運行調試,以本地IP(192.168.6.152)形式訪問
127.0.0.1是回路地址,來檢驗本機TCP/IP協(xié)議棧,實際使用過程中服務端不在本機,是外部地址,要用IP地址測試。
外部用戶采用IP+端口號訪問,如下圖瀏覽器訪問不了,400錯誤。
解決方案:
因為 IIS 7 采用了更安全的 web.config 管理機制,默認情況下會鎖住配置項不允許更改。
以管理員身份運行命令行【此處不要操作】
C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers
如果modules也被鎖定,再運行
C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/modules
客戶端程序:調用接口分為以下幾種情況:
通過Javascript 和 jQuery 調用 Web API
右鍵資源管理器解決方案下面的項目,添加-新建項
將index.html內容替換成:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Product App</title> </head> <body> <div> <h2>All Products</h2> <ul id="products" /> </div> <div> <h2>Search by ID</h2> <input type="text" id="prodId" size="5" /> <input type="button" value="Search" onclick="find();" /> <p id="product" /> </div> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script> <script> var uri = 'api/Products'; $(document).ready(function () { // Send an AJAX request $.getJSON(uri) .done(function (data) { // On success, 'data' contains a list of products. $.each(data, function (key, item) { // Add a list item for the product. $('<li>', { text: formatItem(item) }).appendTo($('#products')); }); }); }); function formatItem(item) { return item.Name + ': $' + item.Price; } function find() { var id = $('#prodId').val(); $.getJSON(uri + '/' + id) .done(function (data) { $('#product').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#product').text('Error: ' + err); }); } </script> </body> </html>
四.發(fā)布web api 并部署
4.1、首先,右鍵項目,選擇發(fā)布:
到這里,程序已經發(fā)布到指定的路徑下了(這里的路徑,可以是本機的文件夾,也可以是服務器上的ftp路徑)
4.2、我們還剩最后一步,就是,在IIS上,把發(fā)布的服務端程序掛上去,不說了,直接上圖:
打開iis,選中網(wǎng)站,右鍵 添加網(wǎng)站,
好了,服務端程序發(fā)布并部署完成。
這個WebAPI就是剛剛我們部署好的,點擊下圖右側的瀏覽*91(http),會打開網(wǎng)頁
總結
到此這篇關于C# webApi創(chuàng)建與發(fā)布、部署、api調用的文章就介紹到這了,更多相關C# webApi創(chuàng)建發(fā)布部署、api調用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
DevExpress之ChartControl創(chuàng)建Drill-Down樣式的Title實例
這篇文章主要介紹了DevExpress之ChartControl創(chuàng)建Drill-Down樣式的Title實現(xiàn)方法,以實例形式講述了創(chuàng)建Drill-Down樣式的Title原理與實現(xiàn)過程,需要的朋友可以參考下2014-10-10運用示例簡單講解C#取消令牌CancellationTokenSource
這篇文章運用示例簡單講解C#取消令牌CancellationTokenSource,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08C#實現(xiàn)在啟動目錄創(chuàng)建快捷方式的方法
這篇文章主要介紹了C#實現(xiàn)在啟動目錄創(chuàng)建快捷方式的方法,涉及C#快捷方式的創(chuàng)建技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09