C# - Method does not contain a definition for an object - c#

I have this block of code:
[HttpDelete("{id}")]
public async Task<IActionResult> Delete([FromBody] MonitorsDeleteRequest request)
{
if (request == null)
{
return BadRequest("Request could not be parsed.");
}
if (request.MonitorId == Guid.Empty)
{
return BadRequest("Query Monitor Id is required.");
}
try
{
await monitoringService.RemoveMonitorAsync(
new RemoveMonitorRequest()
{
MonitorId = new MonitorId(request.MonitorId)
});
return Accepted();
}
catch (Exception ex)
{
logger.LogError($"[{Request.Path.Value}]: {ex.ToString()}");
return StatusCode(500, ex.Message);
}
}
The MonitorId that is inside the RemoveMonitorRequest method (on the left of the equal sign) is underlined in red - Intellisense says "RemoveMonitorRequest does not contain a definition for MonitorId."
Just FYI, the other MonitorId earlier in the code has no Intellisense error.
What can I do to remedy this?

Related

What does it mean by catch (DbUpdateConcurrencyException) when (!TodoItemExists(id))?

What does the below code block mean:
catch (DbUpdateConcurrencyException) when (!TodoItemExists(id))
{
return NotFound();
}
Full sample:
// PUT: api/TodoItems/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> UpdateTodoItem(long id, TodoItemDTO todoItemDTO)
{
if (id != todoItemDTO.Id)
{
return BadRequest();
}
var todoItem = await _context.TodoItems.FindAsync(id);
if (todoItem == null)
{
return NotFound();
}
todoItem.Name = todoItemDTO.Name;
todoItem.IsComplete = todoItemDTO.IsComplete;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException) when (!TodoItemExists(id))
{
return NotFound();
}
return NoContent();
}
This is called an exception filter clause. It is normally used like this:
// without exception filters:
try
{
var file = new StreamReader(myInputStream);
// ....
}
catch (IOException x)
{
// Handle error
}
catch (UnauthorizedAccessException x)
{
// Handle error (same as above)
}
catch (SocketException x)
{
// Handle error (again, same as above)
}
// etc., etc...
// Instead, one can write
try
{
var file = new StreamReader(myInputStream);
// ....
}
catch (Exception x) when (x is SocketException || x is UnauthorizedAccessException || x is IOException)
{
// Handle all expected exception types in one handler
}
I have never seen it being used as in your example. And I'm not sure it is used correctly. What it does is that it only enters the catch clause when TodoItemsExists returns false. That means, on the other hand, that if a DbUpdateConcurrencyException is thrown and TodoItemsExists returns true, the catch handler is not invoked and the exception falls trough, eventually crashing the server task.
I'm not sure about the actual requirement, but I think the following is intented instead:
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TodoItemExists(id))
{
return NotFound();
}
}
return NoContent();
So this will return the appropriate error message to the caller (either NotFound() or NoContent()) when the exception is thrown.
The condition in the when clause can be used to do an additional test whether the handler should be invoked.

Unit Test C# Can we test catch block?

let's say i have a method that logins in;
public async Task<IActionResult> Login()
{
try
{
//my codes..
}
catch(Exception exp)
{
_sLogger.Slack(exp)
return BadRequest();
}
}
i have tested all controllers and methods but i can't test the catch block? i can't throw a exception, how can i do that?
i have tried like this but that doesn't work for me:
public void_WithInvalidData_ThenBadRequest()
{
authController.UnAuthrorize();
var result=(BadRequestResult)authController.Login();
Assert.True(result.StatusCode == (int)HttpStatusCode.BadRequest);
authController.Authorize();
}
Use following code
public async Task<IActionResult> Login()
{
try
{
if (conditions) throw new Exception($"Message"); // throw an exception
}
catch(Exception exp)
{
_sLogger.Slack(exp)
return BadRequest();
}
}

how to return IActionResult compatible UnprocessableEntity - HttpStatusCode (422)

I want to return IActionResult compatible UnprocessableEntity - HttpStatusCode (422) from below catch block the way I am returning `Ok' (200) from try block.
It's giving cast error for below code, What I can do here as I don't want to return 500.
Cannot implicitly convert type 'System.Net.HttpStatusCode' to 'Microsoft.AspNetCore.Mvc.IActionResult'
public IActionResult GetMe()
{
try
{
return Ok();
}
catch (Exception exception)
{
//cast error
// return HttpStatusCode.UnprocessableEntity;
}
}
I think you want return this
public IActionResult GetMe()
{
try
{
return Ok();
}
catch (Exception exception)
{
return UnprocessableEntity();
}
}

API only returns responses with no content

My methods only return responses with no content.
Controller
[HttpGet("Floors/{floorId}", Name = "FloorById")]
public IActionResult GetFloor(int floorId)
{
try
{
Floor floor = _repository.Floor.GetFloor(floorId);
if (floor == null)
return NotFound();
return Ok(floor);
}
catch (Exception e)
{
return StatusCode(500, "text");
}
}
Repository
public Floor GetFloor(int floorId)
{
return _context.Floors.FirstOrDefault(f => f.Id == floorId);
}
Ideally, this code should return an Ok response with the object as well.
Instead, I only get an Ok response when using swagger. Not even the NotFound.
Swagger is unable to determine what type the action returns based on the IActionResult.
Use the ProducesResponseType attribute:
[ProducesResponseType(typeof(Floor), 200)] // <-- THIS
[HttpGet("Floors/{floorId}", Name = "FloorById")]
public IActionResult GetFloor(int floorId) {
try {
Floor floor = _repository.Floor.GetFloor(floorId);
if (floor == null)
return NotFound();
return Ok(floor);
} catch (Exception e) {
return StatusCode(500, "text");
}
}

Why does my ModelState.AddModelError shows error in my index method?

I am new to C# and I encounter this error while doing my code in the
HomeController.cs
public async Task<ActionResult> Index(string searchString)
{
QnAQuery objQnAResult = new QnAQuery();
try
{
if (searchString != null)
{
objQnAResult = await QueryQnABot(searchString);
}
return View(objQnAResult);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error: " + ex);
return View(objQnAResult);
}
}
And when I tried to build the code, there are errors shown in the link.
And it says that The name "ModelState" does not exist in the context.
And The name "View" does not exist in the context.
What could be the possible reason for having such problem?
Thanks!

Categories

Resources