入门:添加一个支持获取单一资源以及支持POST_PUT和DELETE方法
原文地址
WCF Web API支持多个宿主环境:自宿主(windows服务或者控制台)和IIS宿主(asp.net webform/mvc)。这个入门文章主要演示在ASP.NET MVC3网站宿主,主要演示如何在一个Web API上允许更新: 如何检索一个特定项的资源 1、解压启动器代码 要快速开始练习,请到这里下载代码,下载解压后,打开Start目录下的ContactManager项目。代码和入门:构建简单的Web API的主要区别是实体代码重构到一个内存 ContactManagerRepository。 public interface IRepository<T>
{
T Find(int id);
IQueryable<T> FindAll();
void Add(T entity);
Removeint id);
Save();
}
using System;
using System.Collections.Generic;
using System.Linq;
using ContactManager.Repositories;
namespace ContactManager.Infrastructure
{
public abstract class InMemoryRepository<T> : IRepository<T> where T:new()
{
protected List<T> entities;
protected int nextId;
static InMemoryRepository<T> instance;
static object lockObject = new object();
public T int id) {
return entities.SingleOrDefault(e => IsEntityWithId(e,id));
}
public IQueryable<T> FindAll()
{
return entities.AsQueryable();
}
public (T entity) {
OnAdd(entity,nextId++);
entities.Add(entity);
}
int id) {
entities.RemoveAll(e => IsEntityWithId(e,id));
}
() {
throw new InvalidOperationException();
}
protected abstract bool IsEntityWithId(T contact,int id);
OnAdd(T entity,239)">int newId);
}
}
using ContactManager.Infrastructure;
using ContactManager.Resources;
namespace ContactManager.Repositories
{
public interface IContactRepository : IRepository<Contact>
{
}
}
2、启用检索一个单一的资源并和HttpResponseException协同工作 目前我们的API只支持获取一个联系人集合。另一个通常的场景是通过一个URI返回一个单一的资源,如果找不到相关的资源应该返回一个404状态码。 打开ContactsAp.cs [WebGet(UriTemplate="{id}")]
public Contact GetItem(int id)
{
var contact = repository.Find(id);
if (contact == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return contact;
}
注意GET方法接受一个ID参数映射到{id} uri模板参数。如果你的请求API是http://localhost:9000/api/contacts/1 的ID将被设置为1,Web API支持将模板参数自动转换为原生类型int。 运行执行按钮,Contract 1按json格式返回 {"ContactId":1,"Name":"Phil Haack"} 3、添加对POST的支持 以下代码是添加一个新的Post方法,添加一个新的Contract WebInvoke(UriTemplate = "",Method="POST")]
public Contact Post(Contact contact)
{
repository.Add(contact) 上面代码里用到了WebInvokeAttribute,对于所有的HTTP GET以外的其他方法,使用此属性。 该方法指定的参数的必须是大写的。 |
- Swift 4 JSON 解析进阶
- ruby-on-rails – 如何将Karma与Rails资产管道集成?
- ruby-on-rails – 对于sort_by上的nil对象的NoMethodError,
- xcode – Swift 2.2:不再导入GCC_PREPROCESSOR_DEFINITION
- iphone – 如何通过UIImageView(Objective-C)显示UILabel?
- objective-c – iOS:在ImageView上绘制一个矩形并调整边框
- Jenkins - 部署在Tomcat容器里的Jenkins,提示“反向代理设
- c99中隐式声明的功能无效
- xml解析
- ruby-on-rails-3 – 轨道3中的Webmock gem并正确包含它