10

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

[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 的这些方法。谢谢

4

3 回答 3

15

您必须为Transaction.

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

创建新交易 - POST -交易

更新交易 - PUT -交易/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)
{
    //
}

客户端如何使用唯一的 URI 访问 Post 和 Put 的这些方法

POST 和 PUT 不需要唯一的 URI。URI 可以相同。

参考资料:http ://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations

http://msdn.microsoft.com/en-us/library/bb412172(v=vs.90).aspx

于 2012-06-14T16:24:57.330 回答
2

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

这将创建(或更新,如果它已经存在)具有 ID 1234 的事务。这意味着您只能在知道资源的 URL 时使用 PUT。

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

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

请注意,我将 Transaction 复数化,因此它现在代表一个集合。

不是 C# 开发人员,我不知道这映射到 WCF 有多么容易,但这种方法与技术无关。

于 2012-06-14T13:59:01.237 回答
-1

为了制定正确的 url 和 api 设计原则......我发现这本电子书(不是我的!)必读: http: //offers.apigee.com/api-design-ebook-rr/

于 2012-12-01T16:02:20.703 回答