Page inside a Rest Web Api C#

Asked

Viewed 44 times

3

Hello.

I am creating a . Net Core C# Rest project, but I have the following question:

In the processing of the Rest Post, I will return a URL so that the requesting one can view the result data it sent on a page with other information. How can I create within the Rest project this page, so I don’t have to deploy two applications?

Thanks for the help.

  • When you say "REST Project" by chance you mean "Webapi Project"?

  • Yes, a Webapi Project that will act as a Restful HTTP

1 answer

0

In the processing of the Rest Post, I will return a URL so that the request can view the result data it sent in a page with other information

This is just adding an action to a new or existing control. This action should return the object with the necessary information. This practice is in fact considered in RFC2616, especially as regards the creation of new resources

The Location Response-header field is used to redirect the recipient to a Location other than the Request-URI for Completion of the request or Identification of a new Resource. For 201 (Created) Responses, the Location is that of the new Resource which was created by the request.

In free translation:

The location, found in the response header, is used to redirect the receiver to a different request URI location, or identify a new resource. For replies 201 (Created), the Location refers to the resource newly created by the request.

If you want to respect RFC you have to return 201 in your request with the proper location as follows:

[HttpPost]
public IActionResult Post([FromBody] string value)
{
    data.AddOrUpdate(value, true, (e, o) => true);
    var url = Url.Action("Get", "Values", new { id = value });
    Response.Headers.Add("Location", url);
    return StatusCode(201);
}

And you will have the Get request to get the respective resource:

[HttpGet("{id}")]
public ActionResult<string> Get(string id)
{
    if(data.TryGetValue(id, out var e))
    {
        return Ok(e);
    }
    return NotFound();
}

Missing here the dictionary I used to store the values:

private ConcurrentDictionary<string, bool> data = new ConcurrentDictionary<string, bool>();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.