您的位置:首页 > 编程语言 > ASP

ASP.Net Web-api 不可多得的零基础教程7

2018-04-11 22:21 435 查看

Put方法主要用于修改信息。

public HttpResponseMessage Put(int id, Employee employee)
{
    int index = list.ToList().FindIndex(e => e.Id == id);
    if (index >= 0)
    {
        list[index] = employee; // overwrite the existing resource
        return Request.CreateResponse(HttpStatusCode.NoContent);
    }
    else
    {
        list.Add(employee);
        var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, employee);
        string uri = Url.Link("DefaultApi", new { id = employee.Id });
        response.Headers.Location = new Uri(uri);
        return response;
    }
}
本篇的else模块类似于Post方法中的内容,这是因为put在很多人看来也是可以用来创建新的数据的,如果存在就修改,如果不存在就新建。
Request.CreateResponse(HttpStatusCode.NoContent); 这里只是返回了一个没有正文的响应。

类似的操作也可以使用Post来完成。public HttpResponseMessage Post(int id, Employee employee)
{
    int index = list.ToList().FindIndex(e => e.Id == id);
    if (index >= 0)
    {
        list[index] = employee;
        return Request.CreateResponse(HttpStatusCode.NoContent);
    }
    return Request.CreateResponse(HttpStatusCode.NotFound);
}Request.CreateResponse(HttpStatusCode.NoContent); 找到记录,这里只是返回了一个没有正文的响应。

Request.CreateResponse(HttpStatusCode.NotFound); 代表不存在这个记录

本篇结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: