We’re developing an aspnet core website with webapi backend all on a cloud platform. The auth part is implemented with openidconnect and cookies. Every tab is a new application to reduce release and test times. For the website / applications we have a razor class library that contains the main layout. See all posts in this series cloudnative
In Call upstream api with token we described how to get the token in the controller – the backend. Now we need to call the api from jQuery – the frontend. For this we implemented methods on the controller that can be called from jQuery. Because the request is for the samen site, the cookie is send with the request and the controller can access the token for us and do the upstream api request.
// controller = backend
public class RecordController : Controller {
// other methods for aspnet core mvc like Index
// called from frontend with jQuery
[Authorize]
public async Task<IActionResult> CallupstreamApi(
[Required(AllowEmptyStrings = false)] string recordid)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
// call upstream api with IRestClient and recordid
var request = new RestRequest("record/{id}");
request.AddUrlSegment("id", recordid);
var response = await _restClient.ExecuteAsync<record>(request, default);
// return json for easy parsing in jQuery
return Json(response.data);
}
}
// index.cshtml = frontend
function RequestRecordFromUpstreamApi () {
$.ajax({
type: 'GET',
url: '@Url.Action("CallupstreamApi")',
datatype: 'json',
data: {
recordid: 'my_id_for_record_1'
},
success: function (record) { console.log(record.id); },
error: function (xhr, status, error) { console.log(xhr.responseText); }
});
}