简体   繁体   English

任何人都可以向我解释 CreatedAtRoute() 吗?

[英]Can anyone explain CreatedAtRoute() to me?

From the template for Web API 2, a post method is always like this:从 Web API 2 的模板来看,post 方法总是这样的:

[ResponseType(typeof(MyDTO))]
public IHttpActionResult PostmyObject(MyDTO myObject)
{
    ...
    return CreatedAtRoute("DefaultApi", new { id = myObject.Id }, myObject);
}

I don't understand this CreatedAtRoute() method.我不明白这个CreatedAtRoute()方法。 Can anyone explain it to me?谁能给我解释一下?

The CreatedAtRoute method is intended to return a URI to the newly created resource when you invoke a POST method to store some new object. CreatedAtRoute方法旨在在您调用 POST 方法来存储一些新对象时,将 URI 返回到新创建的资源。 So if you POST an order item for instance, you might return a route like 'api/order/11' (11 being the id of the order obviously).因此,例如,如果您发布一个订单项,您可能会返回一个类似 'api/order/11' 的路由(11 显然是订单的 id)。

BTW I agree that the MSDN article is of no use in understanding this.顺便说一句,我同意 MSDN 文章对理解这一点毫无用处。 The route you actually return will naturally depend on your routing setup.您实际返回的路线自然取决于您的路线设置。

When you use CreatedAtRoute , the first argument is the route name of the GET to the resource.当您使用CreatedAtRoute ,第一个参数是GET到资源的路由名称。 The trick that is not so obvious is that, even with the correct method name specified, you must thus use the Name param on the HttpGet attribute for it to work.不太明显的技巧是,即使指定了正确的方法名称,您也必须使用 HttpGet 属性上的 Name 参数才能使其工作。

So if the return in your POST is this:因此,如果您的POST的返回是这样的:

return CreatedAtRoute("Get", routeValues: new { id = model.Id }, value: model);

Then your Get method attribute should look like this even if your method is named Get:那么即使您的方法名为 Get,您的 Get 方法属性也应如下所示:

[HttpGet("{id}", Name = "Get")]

Calls to your Post method will not only return the new object (normally as JSON), it will set the Location header on the response to the URI that would get that resource.对 Post 方法的调用不仅会返回新对象(通常为 JSON),还会在对 URI 的响应中设置 Location 标头以获取该资源。

NOTE the field names in the routeValues field names need to match the binding names in the target route, ie there needs to be a field named id to match the {id} in HttpGet("{id}"注:在字段名routeValues字段名需要在目标路径匹配绑定的名称,即需要有一个字段名为id匹配{id}HttpGet("{id}"

Finally, in some cases, it should be mentioned that the CreatedAtAction helper can be a more direct solution.最后,在某些情况下,应该提到CreatedAtAction助手可以是一个更直接的解决方案。

In .net core WebAPI, you use this method to return a 201 code, which means that the object was created.在 .net core WebAPI 中,你使用这个方法返回一个 201 代码,这意味着对象被创建。

[Microsoft.AspNetCore.Mvc.NonAction]
public virtual Microsoft.AspNetCore.Mvc.CreatedAtRouteResult CreatedAtRoute (string routeName, object routeValues, object content);

As you can see above, the CreatedAtRoute can receive 3 parameters:如上所示,CreatedAtRoute 可以接收 3 个参数:

routeName Is the name that you must put on the method that will be the URI that would get that resource after created. routeName是您必须放在方法上的名称,该方法将成为创建后将获取该资源的 URI。

routeValues It's the object containing the values that will be passed to the GET method at the named route. routeValues它是包含将在命名路由上传递给GET 方法的值的对象。 It will be used to return the created object它将用于返回创建的对象

content It's the object that was created. content它是创建的对象。

The above example shows the implementation of two methods of a simple controller with a simple GET method with the bonded name and the POST method that creates a new object.上面的例子展示了一个简单控制器的两个方法的实现,一个是简单的带有绑​​定名称的 GET 方法,另一个是创建一个新对象的 POST 方法。

[Route("api/[controller]")]
[ApiController]
public class CompanyController : Controller
{
    private ICompanyRepository _companyRepository;

    public CompanyController(ICompanyRepository companyRepository)
    {
        _companyRepository = companyRepository;
    }

    [HttpGet("{id}", Name="GetCompany")]
    public IActionResult GetById(int id)
    {
        Company company = _companyRepository.Find(id);

        if (company == null)
        {
            return NotFound();
        }
        
        return new ObjectResult(company);
    }

    [HttpPost]
    public IActionResult Create([FromBody] Company company)
    {
        if (company == null)
        {
            return BadRequest();
        }

        _companyRepository.Add(company);

        return CreatedAtRoute(
            "GetCompany",
            new { id = company.CompanyID },
            company);
    }
}

IMPORTANT重要的

  1. Notice that the first parameter at CreatedAtRoute (routeName), must be the same at the definition of the Name at the Get method.请注意,CreatedAtRoute (routeName) 的第一个参数必须与 Get 方法中 Name 的定义相同。

  2. The object on the second parameter will need to have the necessary fields that you use to retrieve the resource on the Get method, you can say that it's a subset of the object created itself第二个参数上的对象需要具有用于检索 Get 方法上的资源的必要字段,您可以说它是自己创建的对象的子集

  3. The last parameter is the company object received in the body request in it's full form.最后一个参数是以完整形式在正文请求中收到的公司对象。

FINALY最后

As final result, when the Post to create a new company got made to this API, you will you return a route like 'api/company/{id}' that will return to you the newly created resource作为最终结果,当创建一个新公司的 Post 被发送到这个 API 时,你将返回一个像 'api/company/{id}' 这样的路由,它将返回给你新创建的资源

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

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