Page inside a Rest Web Api C#

Question:

Hi.

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

When processing the Post do Rest, I will return a URL so that the requesting party can view the result data he sent in a page with other information. How can I create this page inside the Rest project, so I don't have to deploy two applications?

Thanks for the help.

Answer:

When processing the Post do Rest, I will return a URL so that the requesting party can view the result of the data he sent on 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 indeed considered in RFC2616 , especially when it comes to creating new features

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 location other than the request URI, or to identify a new resource. For 201 (Created) responses, Location refers to the resource newly created by the request.

If you want to respect the RFC, you must 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();
}

The dictionary I used to store the values ​​is missing here:

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