ASP.net Core RC2 Web API POST-何时使用Create,CreatedAtAction和CreatedAtRoute? [英] ASP.net Core RC2 Web API POST - When to use Create, CreatedAtAction, vs. CreatedAtRoute?

查看:340
本文介绍了ASP.net Core RC2 Web API POST-何时使用Create,CreatedAtAction和CreatedAtRoute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些功能的根本区别是什么?我所知道的是所有这三个结果都为201,这适合于成功的POST请求.

What are the fundamental differences of those functions? All I know is all three result in a 201, which is appropriate for a successful POST request.

我只遵循我在网上看到的示例,但是他们并没有真正解释他们为什么做自己在做的事情.

I only follow examples I see online, but they don't really explain why they're doing what they're doing.

我们应该为GET提供一个名称(1条记录,id):

We're supposed to provide a name for our GET (1 record by id):

[HttpGet("{id}", Name="MyStuff")]
public async Task<IActionResult> GetAsync(int id)
{
     return new ObjectResult(new MyStuff(id));
}

命名此get函数的目的是什么,除了下面的POST函数可能"需要它外:

What is the purpose of naming this get function, besides that it's "probably" required for the POST function below:

[HttpPost]
public async Task<IActionResult> PostAsync([FromBody]MyStuff myStuff)
{
     // actual insertion code left out

     return CreatedAtRoute("MyStuff", new { id = myStuff.Id }, myStuff);
}

我注意到CreatedAtRoute还有一个重载,它没有采用路由名.

I notice that CreatedAtRoute also has an overload that does not take in the route name.

还有CreatedAtAction带有相似的参数.为什么存在这种变体?

There is also CreatedAtAction that takes in similar parameters. Why does this variant exist?

还有Created,它需要一个URL和我们要返回的对象.我可以只使用这种变体并提供一个伪造的URL并返回我想要的对象并完成它吗?

There is also Created which expects a URL and the object we want to return. Can I just use this variant and provide a bogus URL and return the object I want and get it done and over with?

我不确定为什么有这么多的变体只是为了能够将201返回给客户端.在大多数情况下,我要做的就是返回"app-assigned"(很可能来自数据库)唯一的ID或具有最少信息的我的实体版本.

I'm not sure why there are so many variants just to be able to return a 201 to the client. In most cases, all I want to do is to return the "app-assigned" (most likely from a database) unique id or a version of my entity that has minimal information.

我认为,最终201响应应该"创建一个位置标头,其中包含新创建资源的URL,我相信这3个参数及其重载最终都可以完成.为什么我总是要返回位置标头?我的JavaScript客户端,本机移动设备和桌面应用程序从未使用过它.例如,如果我发出HTTP POST来创建计费对帐单并将其发送给用户,那么这样的位置URL是什么? (我很抱歉没有更深入地了解互联网的历史以找到答案.)

I think that ultimately, a 201 response "should" create a location header which has the URL of the newly-created resource, which I believe all 3 and their overloads end up doing. Why should I always return a location header? My JavaScript clients, native mobile, and desktop apps never use it. If I issue an HTTP POST, for example, to create billing statements and send them out to users, what would such a location URL be? (My apologies for not digging deeper into the history of the Internet to find an answer for this.)

为什么要为动作和路线创建名称?动作名称和路线名称有什么区别?

Why create names for actions and routes? What's the difference between action names and route names?

对此我感到困惑,因此我求助于返回Ok(),该返回的200不适用于POST.

I'm confused about this, so I resorted to returning the Ok(), which returns 200, which is inappropriate for POST.

推荐答案

这里有几个不同的问题可能应该分开,但我认为这涵盖了您的大部分问题.

There's a few different questions here which should probably be split out, but I think this covers the bulk of your issues.

为什么要为动作和路线创建名称?动作名称和路线名称有什么区别?

首先,动作和路线非常不同.

First of all, actions and routes are very different.

动作存在于控制器上.一条路线指定了一个完整的终点,该终点包括一个控制器,一个动作以及可能的其他附加路线参数.

An Action lives on a controller. A route specifies a complete end point that consists of a Controller, and Action and potentially additional other route parameters.

您可以给路由命名,以便在应用程序中引用它.例如

You can give a name to a route, which allows you to reference it in your application. for example

routes.MapRoute(
  name: "MyRouteName",
  url: "SomePrefix/{action}/{id}",
  defaults: new { controller = "Section", action = "Index" }
);

此问题涵盖了操作名称的原因: ActionName的用途

The reason for action names are covered in this question: Purpose of ActionName

它允许您以数字开始操作或在标识符中包含.net不允许的任何字符.-最常见的原因是它允许您使用相同签名的两个Action (请参阅任何脚手架控制器的GET/POST Delete操作)

It allows you to start your action with a number or include any character that .net does not allow in an identifier. - The most common reason is it allows you have two Actions with the same signature (see the GET/POST Delete actions of any scaffolded controller)

这些功能的基本区别是什么?

这3个函数基本上执行相同的功能-返回201 Created响应,其中Location标头指向新创建的响应的url,并且对象本身在正文中.该url应该是GET请求将返回对象url的URL.这将被视为RESTful系统中的正确"行为.

These 3 functions all perform essentially the same function - returning a 201 Created response, with a Location header pointing to the url for the newly created response, and the object itself in the body. The url should be the url at which a GET request would return the object url. This would be considered the 'Correct' behaviour in a RESTful system.

对于问题中的示例邮政编码,您实际上想使用CreatedAtAction.

For the example Post code in your question, you would actually want to use CreatedAtAction.

[HttpPost]
public async Task<IActionResult> PostAsync([FromBody]MyStuff myStuff)
{  
   // actual insertion code left out

   return CreatedAtAction("MyStuff", new { id = myStuff.Id }, myStuff);
}

假设您配置了默认路由,这将在同一控制器上添加一个指向MyStuff操作的Location标头.

Assuming you have the default route configured, this will add a Location header pointing to the MyStuff action on the same controller.

如果您希望位置网址指向特定的路线(如我们之前所定义,则可以使用例如

If you wanted the location url to point to a specific route (as we defined earlier, you could use e.g.

[HttpPost]
public async Task<IActionResult> PostAsync([FromBody]MyStuff myStuff)
{  
   // actual insertion code left out

   return CreatedAtRoute("MyRouteName", new { id = myStuff.Id }, myStuff);
}

我可以只使用此变体并提供一个伪造的URL并返回我想要的对象并完成它吗?

如果您真的不想使用CreatedResult,则可以使用简单的StatusCodeResult,它会返回201,而没有Location标头或正文.

If you really don't want to use a CreatedResult, you can use a simple StatusCodeResult, which will return a 201, without the Location Header or body.

[HttpPost]
public async Task<IActionResult> PostAsync([FromBody]MyStuff myStuff)
{  
  // actual insertion code left out

  return StatusCode(201);
}

这篇关于ASP.net Core RC2 Web API POST-何时使用Create,CreatedAtAction和CreatedAtRoute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆