POST/PUT Restful服务的URI模板

10

我要编写一个RESTful API,我的需求是对“Transaction”对象调用方法,我想知道应该如何使用适当的URI模板调用Post/PUT方法,以便在不使用Uri映射中的“动词”的情况下创建/更新Transaction资源。

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/Transaction/{**What to write here ????**}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public Transaction AddTransaction(Transaction transaction)
{
    return AddTransactionToRepository(transaction);
}

[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "/Transaction/{**What to write here ????**}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
public Transaction UpdateTransaction(Transaction transaction)
{
    return UpdateTransactionInRepository(transaction);
}
请注意,我希望应用最佳实践进行URI映射,并且不想在其中使用“动词”,只想使用“名词”。同时,请告诉我客户端如何访问这些具有唯一URI的Post和Put方法。谢谢。
3个回答

15

针对Transaction,您需要按照以下方式映射URI。

通过ID获取交易 - GET - transaction/id

创建新交易 - POST - transaction

更新交易 - PUT - transaction/id

删除交易 - DELETE - transaction/id

您的URI模板必须更改为以下内容。

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/Transaction", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public Transaction AddTransaction(Transaction transaction)
{
    //
}

[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "/Transaction/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
public Transaction UpdateTransaction(int id, Transaction transaction)
{
    //
}
你不需要为POST和PUT使用唯一的URI,这些URI可以相同。参考:http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operationshttp://msdn.microsoft.com/en-us/library/bb412172(v=vs.90).aspx

感谢马克的澄清,我对客户端如何以更可读的方式进行通信有些困惑,但我猜想客户端在调用API方法时需要指定不同的操作,即post、put、delete,但调用相同的URL。 - MSUH
@Mark,为什么这两种方法都返回Transaction对象?我知道POST方法可能需要这个,因为Id可能是数据库中的自动生成数字,但PUT方法为什么也要返回呢?谢谢。 - RobJohnson
1
第二个示例将编译,但无法激活,因为UriTemplate路径段的变量必须是“string”。 - Rajiv

2

PUT用于创建或更新已知资源,例如:PUT /Transactions/1234

这将创建(如果尚不存在)带有ID 1234的事务。这意味着只有当您知道资源的URL时才能使用PUT。

POST创建一个新的子资源,例如:POST /Transactions/

这将创建一个新的事务资源。

请注意,我使用了复数形式的Transaction,因此现在它表示一个集合。

作为一名非C#开发人员,我不知道这是否与WCF很容易映射,但这种方法是与技术无关的。


-1

链接似乎已经失效。 - JoseHdez_2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接