简体   繁体   English

asp.net mvc和web api哪个是更好的Http POST或PUT

[英]asp.net mvc and web api which is better Http POST or PUT

I have an application of type asp.net mvc and web api. 我有一个类型为asp.net mvc和web api的应用程序。 I m little bit confused over http post and http put. 我对http post和http put有点困惑。 When to use what and what is the pros and cons of each. 什么时候使用什么,各有利弊。 I have gone through many blogs but no solid reason what is designed for what. 我已经浏览了很多博客,但没有充分理由为什么设计。

Use POST where you would have to create completely new record from scratch. 使用POST ,您必须从头开始创建全新的记录。 Use PUT where you would have to update existed record in your database 使用PUT ,您必须更新数据库中的现有记录

Here are Differences between PUT & POST 这是PUT和POST之间的差异

   `POST is Not idempotent`--> 

Means running POST operation again and again will create new instance everytime when you run call it. 一次又一次地运行POST操作意味着每次运行时都会创建新实例。

`PUT is Idempotent`--> 

PUT is Idempotent operation calling PUT again and again will result same result. PUT是一次又一次地调用PUT的幂等操作将导致相同的结果。

So POST is not idempotent while PUT is idempotent. 所以POST不是幂等的,而PUT是幂等的。

`There is also PATCH` -->

Use patch when you would have to update only few properties of your model.In other words Partial Updates. 当您只需要更新模型的少数属性时使用补丁。换句话说,部分更新。

Put simply (no pun intended): 简单地说(没有双关语):

POST is usually used to CREATE new objects. POST通常用于创建新对象。

PUT is usually used to UPDATE existing objects PUT通常用于更新现有对象

Using the correct HTTP verbs allows you to publish a cleaner API and negates the need for encoding intent within the endpoint (url). 使用正确的HTTP谓词允许您发布更清晰的API,并且无需在端点(url)中编码意图。 For example, compare: 例如,比较:

Using the correct verbs: 使用正确的动词:

GET    api/user/12345
POST   api/user/12345
PUT    api/user/12345
DELETE api/user/12345

Hacking the endpoint: 黑客端点:

GET  api/user/12345
POST api/user/12345/create
POST api/user/12345/update
POST api/user/12345/delete

I think the only Cons of using PUT etc are that not all developers are familiar with them and some third party software may not support them or at least it may not be as easy as using the more familiar verbs like GET & POST . 我认为使用PUT等唯一的缺点是并非所有开发人员都熟悉它们,而且某些第三方软件可能不支持它们,或者至少它可能不像使用更熟悉的动词如GETPOST那么容易。

For example, I had a problem a few weeks ago when a proxy was placed in front of an API just before it was to go live and the proxy didn't support the HTTP PUT verb (maybe a config issue - but we didn't have access to the proxy to fix it) so we had to tweak the API and change it to POST at the last minute (which also meant we had to change the clients (mobile apps) that were using it). 例如,几周前我遇到一个问题,就是在它出现之前将代理放在API前面并且代理不支持HTTP PUT动词(可能是配置问题 - 但我们没有有权访问代理来修复它)所以我们不得不调整API并在最后一刻将其更改为POST (这也意味着我们必须更改正在使用它的客户端(移动应用程序))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM