一.創(chuàng)建web api項(xiàng)目
1.1、項(xiàng)目創(chuàng)建
MVC架構(gòu)的話,它會(huì)有view-model-control三層,在web api中它的前端和后端是分離的,所以只在項(xiàng)目中存在model-control兩層
1.2、修改路由
打開App_Start文件夾下,WebApiConfig.cs ,修改路由,加上{action}/ ,這樣就可以在api接口中通過接口函數(shù)名,來導(dǎo)向我們希望調(diào)用的api函數(shù),否則,只能通過controller來導(dǎo)向,就可能會(huì)造成有相同參數(shù)的不同名函數(shù),沖突。其中,{id}是api接口函數(shù)中的參數(shù)。
?
默認(rèn)路由配置信息為:【默認(rèn)路由模板無法滿足針對(duì)一種資源一種請(qǐng)求方式的多種操作。】
WebApi的默認(rèn)路由是通過http的方法(get/post/put/delete)去匹配對(duì)應(yīng)的action,也就是說webapi的默認(rèn)路由并不需要指定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 配置和服務(wù)
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
//修改路由,加上{action}/ ,這樣就可以在api接口中通過接口函數(shù)名,來導(dǎo)向我們希望調(diào)用的api函數(shù),
//否則,只能通過controller來導(dǎo)向,就可能會(huì)造成有相同參數(shù)的不同名函數(shù),沖突。其中,{id}是api接口函數(shù)中的參數(shù)
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
二.測(cè)試案例
寫一個(gè)測(cè)試的api函數(shù),并開始執(zhí)行(不調(diào)試)
2.1、我們?cè)趍odel文件夾中添加一個(gè)類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、我們?cè)趍odel文件夾中添加一個(gè)類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="動(dòng)漫",price=28},
new movie { name="云南蟲谷",director="佚名",actor="潘粵明",type="驚悚",price=32},
new movie { name="沙海",director="佚名",actor="吳磊",type="驚悚",price=28},
new movie { name="千與千尋",director="宮崎駿",actor="千尋",type="動(dòng)漫",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);
}
}
}
這樣就完成了一個(gè)web?api實(shí)例的編寫
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();
//這邊可以進(jìn)行任意操作,比如數(shù)據(jù)存入或者取出數(shù)據(jù)庫等
return res;
}
}
}
三.本地調(diào)試
3.1?運(yùn)行調(diào)試,以本地 localhost(或127.0.0.1)形式訪問
①點(diǎn)擊工具欄【IIS Express】
②瀏覽地址輸入接口,看是否可以訪問
localhost:44381/api/products/GetAllProducts
注意:
這里的路徑是寫你的控制器前綴名稱(Control文件下的productsController控制器文件的前綴)
https://localhost:44381/api/Test/GetAllMovies
2)直接在瀏覽器中調(diào)試也行
想要調(diào)試的值,可以將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 配置和服務(wù)
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
//修改路由,加上{action}/ ,這樣就可以在api接口中通過接口函數(shù)名,來導(dǎo)向我們希望調(diào)用的api函數(shù),
//否則,只能通過controller來導(dǎo)向,就可能會(huì)造成有相同參數(shù)的不同名函數(shù),沖突。其中,{id}是api接口函數(shù)中的參數(shù)
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//去掉xml返回格式、設(shè)置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項(xiàng)目實(shí)例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
{
//檢查用戶名是否已注冊(cè)
private ApiTools tool = new ApiTools();
// [HttpPost]
[HttpGet]
public HttpResponseMessage CheckUserName(string _userName)
{
int num = UserInfoGetCount(_userName);//查詢是否存在該用戶
if (num > 0)
{
return tool.MsgFormat(ResponseCode.操作失敗, "不可注冊(cè)/用戶已注冊(cè)", "1 " + _userName);
}
else
{
return tool.MsgFormat(ResponseCode.成功, "可注冊(cè)", "0 " + _userName);
}
}
private int UserInfoGetCount(string username)
{
//return Convert.ToInt32(SearchValue("select count(id) from userinfo where username='" + username + "'"));
return username == "admin" ? 1 : 0;
}
}
}
添加返回(響應(yīng))類ApiTools
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
namespace WebAPI.Models
{
//添加返回(響應(yīng))類
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)本地調(diào)試,調(diào)用Web API接口
運(yùn)行調(diào)試,以本地 localhost(或127.0.0.1)形式訪問
①點(diǎn)擊工具欄【IIS Express】
②瀏覽地址輸入接口,看是否可以訪問
https://localhost:44381/api/UserInfo/CheckUserName?_userName=wxd
3.2 運(yùn)行調(diào)試,以本地IP(192.168.6.152)形式訪問
127.0.0.1是回路地址,來檢驗(yàn)本機(jī)TCP/IP協(xié)議棧,實(shí)際使用過程中服務(wù)端不在本機(jī),是外部地址,要用IP地址測(cè)試。
外部用戶采用IP+端口號(hào)訪問,如下圖瀏覽器訪問不了,400錯(cuò)誤。
?
解決方案:
因?yàn)?IIS 7 采用了更安全的 web.config 管理機(jī)制,默認(rèn)情況下會(huì)鎖住配置項(xiàng)不允許更改。
以管理員身份運(yùn)行命令行【此處不要操作】
C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers
如果modules也被鎖定,再運(yùn)行
C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/modules
客戶端程序:調(diào)用接口分為以下幾種情況:
通過Javascript 和 jQuery 調(diào)用 Web API
右鍵資源管理器解決方案下面的項(xiàng)目,添加-新建項(xiàng)
將index.html內(nèi)容替換成:
<!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、首先,右鍵項(xiàng)目,選擇發(fā)布:
到這里,程序已經(jīng)發(fā)布到指定的路徑下了(這里的路徑,可以是本機(jī)的文件夾,也可以是服務(wù)器上的ftp路徑)
4.2、我們還剩最后一步,就是,在IIS上,把發(fā)布的服務(wù)端程序掛上去,不說了,直接上圖:
打開iis,選中網(wǎng)站,右鍵 添加網(wǎng)站,?
?好了,服務(wù)端程序發(fā)布并部署完成。
這個(gè)WebAPI就是剛剛我們部署好的,點(diǎn)擊下圖右側(cè)的瀏覽*91(http),會(huì)打開網(wǎng)頁文章來源:http://www.zghlxwxcb.cn/news/detail-753865.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-753865.html
到了這里,關(guān)于[入門一]C# webApi創(chuàng)建、與發(fā)布、部署、api調(diào)用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!