WebApi一个控制器中定义多个Get方法。
问题:怎样解决一个ApiController中定义多个Get方法或者Post方法?
答:要想实现一个ApiController中定义多个Get方法或者Post方法,则需要在WebApiConfig类中的Register()中自定义路由规则,规则中显示指定action。
示例:
// Web API 路由
config.MapHttpAttributeRoutes();
//自定义指定action的路由。2017.11.11 14:56 added by longdb
config.Routes.MapHttpRoute(
name: "WebApiTest",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//默认路由规则。
//config.Routes.MapHttpRoute(
// name: "WebApiTest",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
ApiController中两个Get方法:
public class WebApiTestController : ApiController
{
[HttpGet]
public string GetString()
{
string sql = @"SELECT TOP 10 0 cnt, '1' ck,no,name,object,score,id FROM dbo.infor
WHERE id IN(SELECT TOP 10 id FROM dbo.infor ORDER BY id)
UNION ALL
SELECT COUNT(id) cnt,'1' ck,'' no, '' name,'' object,'' score,'' id FROM dbo.infor";
DataTable dt = DBHelper.DBExecuteByAdapter(sql);
return JSONInterFace.DataTableToJsonWithJsonNet(dt);//.Rows.Count.ToString();
}
[HttpGet]
public IHttpActionResult GetStudentInfor()
{
List<StudentModel> stlists = new List<StudentModel>();
stlists.Add(new StudentModel { hno = "1001", hname = "龙大炳", hobject = "WebApi", hscore = "90" });
stlists.Add(new StudentModel { hno = "1002", hname = "龙大炳", hobject = "Ajax", hscore = "80" });
stlists.Add(new StudentModel { hno = "1003", hname = "龙大炳", hobject = "SignalR", hscore = "88" });
return Json<List<StudentModel>>(stlists);//, Newtonsoft.Json.JsonSerializer.CreateDefault.stlists);
}
}
注意点:不能定义重复名称的路由,路由名称必须唯一。