I have 3-tier project, I do database / API / MVC on ASP.NET Core; all controllers are working correctly but this connection of this API controller doesn't work.
This is my business layer function:
public List<Ticket> ViewTickets()
{
try
{
using (var db = new MaintenanceSysContext(_options))
{
List<Ticket> tickets = null;
List<int> ticketsId = db.Tickets.SelectMany(t => t.backOfficesTickets).Where(u => u.BackOfficeId == _backOfficeEntry.GetUserId()).Select(t => t.TicketId).ToList();
foreach( var i in ticketsId)
{
tickets = db.Tickets.Where(t => t.Id == i).ToList();
}
if (tickets != null)
{
return tickets;
}
else
{
return null;
}
}
}
catch (Exception)
{
throw;
}
}
And this is the controller in the API:
[HttpGet]
[Route("[action]")]
[ActionName("ViewTickets")]
public IActionResult ViewTickets()
{
var tickets = _buildingManager.ViewTickets();
return Ok(tickets);
}
Here's my ASP.NET Core MVC httpClient
connection:
url base:
HttpClient client = new HttpClient();
public static string baseUrl = "http://localhost:16982/api/BuildingManagerAPI/";
ASP.NET Core MVC controller:
[HttpGet]
public async Task<ActionResult> GetTickets()
{
List<Ticket> TicketList = new List<Ticket>();
using (client)
{
var accessToken = HttpContext.Session.GetString("Token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var httpResponse = await client.GetAsync(baseUrl + "ViewTickets");
if (httpResponse.IsSuccessStatusCode)
{
TicketList = await httpResponse.Content.ReadAsAsync<List<Ticket>>();
}
}
return Json(TicketList, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
In the httpResponse.IsSuccessStatusCode
I get back a value of false
while API works correctly AND returns a proper response when testing in Postman. I don't know what the problem of my connection is.
UPDATE:
Postman request output:
[
{
"Id": 1,
"BeneficiaryID": 4,
"BeneficiaryUser": null,
"backOfficesTickets": null,
"StatusID": 2,
"status": null,
"ApprovalState": 2,
"Date": "2021-08-22T00:00:00",
"Picture": null,
"MaintenanceTypeID": 1,
"maintenanceType": null,
"Description": "krng",
"BuildingManagerComment": null,
"FloorId": 1,
"floor": null,
"IsCancelled": false,
"CancellationReasonID": null,
"cancelationReason": null,
"RejectedBy": null,
"UserRejected": null,
"RejectionReason": null,
"CreatedBy": 4,
"CreatedTime": "0001-01-01T00:00:00",
"UpdatedBy": 0,
"UpdatedTime": "0001-01-01T00:00:00",
"IsDeleted": false
}
Red Point doesn't get uri (client base uri=null) then IsSuccessStatusCode set as NULL.
The Problem Was in Token (Doesn't carry claim) we fix it. Thanks For All.