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

查看:31
本文介绍了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 返回给客户端.在大多数情况下,我想要做的就是返回应用程序分配的"(最有可能来自数据库)唯一 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 不允许在标识符中的字符. - 最常见的原因是它允许您有两个具有相同签名的操作(请参阅任何脚手架控制器的 GET/POST 删除操作)

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);
}

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

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

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

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天全站免登陆