1、建議使用異步接口async Task<>
public async Task<IHttpActionResult> Get()
如果返回的是IEnumerable請使用:
return Ok<IEnumerable<ListSitesDetails>>(sites);
如果返回是實體請使用:
return Ok(entity);
此返回常常在獲取一個類型值時使用:
public async Task<IHttpActionResult> Get(int id)
如果僅僅返回一個成功結果200就是直接Ok();就行了
如果想返回一個實體類又想返回一個地址路由請使用:
return CreatedAtRoute("DefaultApi", new {controller="Home",id=sites.Id }, sites);
轉到api/Home/id上,並返回剛剛添加的sites新內容
return Created("http://www.*.com",sites);
返回sites和位置
2、在WebApi里怎樣自定義方法?怎樣調用方法?
public async Task<IHttpActionResult> GetTest(string account) { string restmsg = await UserLogin("十五里元中學", account, "0000"); return Ok(restmsg); }
如果是get訪問則所有方法前面都要加Get; Post則要加Post;可是調用的時候要去掉Get/Post
比如上面的代碼要調用它要這樣:/api/users/test?account=james
當然你也可以添加路由改變訪問方式:
[Route("api/users/gettest/{account}")] public async Task<IHttpActionResult> GetTest(string account) { string restmsg = await UserLogin("十五里元中學", account, "0000"); return Ok(restmsg); }
上面要調用則使用:/api/users/test/james方式
-------------------------------------------------------------------------------------
再來看Post示例
[HttpPost] public async Task<IHttpActionResult> PostLogin(string school)
這個表示是Post訪問調用,它的調用為:/api/Users/login?school=十五里元中學
如果多個參數,建議直接使用類型傳值,不要使用string。比如:
[HttpPost] public async Task<IHttpActionResult> PostLogin(Item item)
public class Item { public string school{get;set;} public string account{get;set;} public string password{get;set;} }
調用:
var item = {'school':'十五里元中學','account':'james','password':'0000'}; return $http({ url: 'api/user/login', method: 'POST', type: 'application/json', data: item }).then(function (user) { // check the user is null or not and take action }).error(function (error) { alert('invalid'); });