一、項(xiàng)目的搭建
1.首先新建一個(gè)ASP.NET應(yīng)用程序。
2.在新建ASP.NET項(xiàng)目界面,按照如下步驟進(jìn)行。
點(diǎn)擊確定后,后續(xù)那個(gè)讓你使用Azure的界面直接取消即可。
3.新建后的界面如下
?
鼠標(biāo)右擊Controllers 文件夾,在添加項(xiàng)后面選擇控制器。
選擇如下控制器,點(diǎn)擊添加按鈕。
根據(jù)需求修改名稱(后續(xù)會(huì)使用到①)
?在新添加到控制器中寫入如下代碼(我這邊寫的很簡(jiǎn)單,方便大家的了解)
函數(shù)名為MyExample,參數(shù)名為(param1,param2)(后續(xù)會(huì)使用到②)
用的是HttpGet,也可以使用HttpPost等。
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;
}
}
切換到WebApiConfig.cs,修改代碼如下
public static void Register(HttpConfiguration config)
{
// Web API 配置和服務(wù)
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
最后在項(xiàng)目屬性界面,將web的啟動(dòng)操作選成如下所示。
二、調(diào)試
點(diǎn)擊調(diào)試按鈕
桌面右下角的IIS里面會(huì)有調(diào)試的網(wǎng)站,比如我的為http://localhost:****
項(xiàng)目WebApiConfig.cs中,修改了Register函數(shù)的routeTemplate:api/{controller}/{action}/{id}
{controller}為在“一、項(xiàng)目創(chuàng)建”中后續(xù)會(huì)使用到①建立的控制器MyController(只取My)
{action}為在“一、項(xiàng)目創(chuàng)建”中后續(xù)會(huì)使用到②函數(shù)名MyExample
{id}為為在“一、項(xiàng)目創(chuàng)建”中后續(xù)會(huì)使用到②參數(shù)名(param1,param2)
于是,我么得到了調(diào)試的網(wǎng)址:
http://localhost:****/api/My/MyExample?param1=¶m2=
(1)如果有Postman,可以在Postman中調(diào)試
?文章來源地址http://www.zghlxwxcb.cn/news/detail-421291.html
(2)如果沒有,也沒有關(guān)系,直接在瀏覽器中調(diào)試也行
如果只想要調(diào)試的值,可以將WebApiConfig.cs的代碼修如下
public static void Register(HttpConfiguration config)
{
// Web API 配置和服務(wù)
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
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,顯示成功
文章來源:http://www.zghlxwxcb.cn/news/detail-421291.html
?
到了這里,關(guān)于c# WebApi的搭建和調(diào)試(超級(jí)簡(jiǎn)單)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!