Health check, ASP.NET Web API - c#

In my work I was asked to implement health checks into an ASP.NET Web API 2 written in C#. I have searched but all the documentation is for ASP.NET Core and its implementation, does anyone know how to implement health check featurs in the classic / full .NET Framework?

I agree with Igor. Here's a concrete application of what he suggested (obviously, there are other ways to do this, but this is the best way I know how to keep it clear and honor separation of concerns):
Create a new controller. In this example, I'll call it HealthController
Add an action to the controller, and annotate it with [HttpGet]
Place logic inside the action that checks for the stability of external dependencies. For example, if disk access is critical for your API, run a test or two to make sure that the disk is responding like you need it to. If you need to be able to query a database, make a sample query, and make sure it's successful. This part is completely custom and really depends on your API and how it needs to perform.
public class HealthController : ApiController
{
[HttpGet]
public IHttpActionResult Check()
{
// Add logic here to check dependencies
if (/* successful */)
{
return Ok();
}
return InternalServerError(); // Or whatever other HTTP status code is appropriate
}
}
Have an external service issue a GET request to your endpoint (currently at https://whatever.your.domain.is/Health/Check) and report back when it doesn't receive 200 OK for some amount of time.
I've used Amazon CloudWatch in the past and I've been happy with it. There are going to be other services out there that will do this for you, but I don't have any experience with them.

Related

How should I send HTTP Request in Clean Architecture in C#

I'm new in DDD/ Clean Architecture
I'm trying to implement this architecture in a new from scratch application and I feel confused in some points.
I'm trying to make the best choice to not regret it as application will start growing.
Probably my question is a bit stupid, but again i'm new in DDD and trying to make the best choices.
I'm trying to stick to this example https://github.com/ardalis/CleanArchitecture from Ardalis
Here is my model/problem simplified
-ApplicationAggregateRoot
---Application
---Instance
Application has a list of Instance.
Now I have to do an HTTPRequest "/operationA" on the Instance, this can be done by my blazor UI or by my API via controllers.
The result of this HTTP Request "/operationA" will have to be saved in my repository, and do other stuff, so from what I understood here I need an event when I have the HTPP Response something like "OperationAFinishedEvent"
What I don't really know how to figure it out is how should I make this call in my controller/blazor for example.
Should I do (pseudo code):
A)
_repository.GetApplicationById(1).Instances.First(i => i == id).OperationA()
and have some event raised in OperationA() Method of Instance
(something like "OperationASentEvent") which will be wired to a handler that will call _httpClient.OperationA(instance.Url)
Or should I pass by a domain service class for doing the call instead of an event like:
B)
class Controller
{
OperationA(Instance instance)
{
_instanceService.OperationA(instance)
}
}
class InstanceService
{
void OperationA(Instance instance)
{
_httpClient.OperationA(instance.Url);
new OperationAFinishedEvent(instance);
}
}
C) Or call directly
_httpClient.OperationA(instance.Url);
new OperationAFinishedEvent(instance);
from both controller and blazor
Or maybe something else ?
Thank's
It sounds like you have a Blazor client side app as well as a server-side app that you access via an API. So let's address both sides of the app.
In Blazor, you're typically going to minimize application logic and mostly just make calls to the API. So the code required to kick off an operation for an application instance in Blazor should look like this:
var result = await _httpClient.PostAsync(endpointUrl, data);
If that's a long-running process, you might bet back a result that provides you with another endpoint you can query for status. Otherwise the result should just let you know if the process completed successfully or not.
In your API, you will have various endpoints. Normally these endpoints correspond to resources and operations you can take to alter the state of these resources. Your API resources usually correspond to your domain model, but not always 100%. You should generally avoid using HTTP APIs for Remote Procedure Call (RPC) operations, since they're not really designed for that purpose. Instead, think in terms of requests and responses, typically. Imagine you're trying to get your city government to do something, and the way you do that is by filling out a form to hand to a clerk. Then when the action has been completed, they hand you back some more paperwork. The clerk is your API. The papers are your request and response objects. The actual action - the "instance operation" is happening back inside the office where you don't see it as a client, and none of your interactions are with it directly.
So you might have a resource like this:
/Applications/123/Instances/234/PendingOperations
You can list pending operations. You can POST a new operation request. Etc. There might also be a resource for .../CompletedOperations or you might get back an id for your pending operation that you can later use to view its status. The idea is to have an endpoint that represents a noun (a resource) and not a verb (do something).
Hope that helps!
Your domain layer (aggregate root is in there) should only be concerned about their internal state.
The applications layer (where you also use the repository) can call an interface to an other service, using the data from the aggregate root.
The interface is then implemented in a seperate layer.

How to make reusable controllers in Asp.Net Core

I'm working on my first Asp.Net Core project, which is to support both a web client, and a Game client (written in Unity).
Now, I started with the default Asp.Net Core Web Application project template provided by Visual Studio 2015, including authentication for Individual User Accounts.
Most, if not all of the generated controllers are returning views, following this pattern in general:
[HttpGet]
[AllowAnonymous]
public IActionResult Get()
{
//Do something smart
return View();
}
This method returns a View as you can see and all is good when requested by the web client.
But what if the Game is sending a request to the same method?
In that case a JSON response is expected (not a View/html document), and my question is what is the recommended "pattern" for supporting this in Asp.Net Core?
Should I place the api returning JSON in separate controllers, hence duplicating some logic? It doesn't feel right to me...
Or should I check the request for an expected response format, and implement logic for returning different responses based on this?
I don't particularly like that approach either...
To me, it seems Asp.Net Core messes things up by providing UI formatted responses directly from the API, but it might be something I've missed here...
Any pointers?
You could move the logic into a class to be called by the controller if you want separate controllers or actions for the Webpage and game.
This would be better and follow the single responsibility rule rather than one action returning two response types
When the return type is IActionResult you can also return Json messages for example as return Json(myReturnObject). You can add an if to return a JSON message and when it is false it will return the view.
You can add an if based on X-Requested-With:
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return Json(myObject);
}
What I would recommend is to split the requests in different controller methods by response type and add the shared code/logic in a private method or to another class, probably you will use this elsewhere too. By doing this you will be able to do proper tests and won't get confused when it will return the view or a json message.
Hope this helps.

How to properly make a call to a Web API

In the ASP .NET website they have an example of how to call a Web API from a .NET Client.
They have this method to make a call which creates a new Product:
static async Task<Uri> CreateProductAsync(Product product)
{
HttpResponseMessage response = await client.PostAsJsonAsync("api/products", product);
response.EnsureSuccessStatusCode();
// Return the URI of the created resource.
return response.Headers.Location;
}
This is like the usual way to make any call to any API in any language or framework, but I see a lot of problems in this line:
HttpResponseMessage response = await client.PostAsJsonAsync("api/products", product);
If the "path" parameter is a string, there is no way to detect possible errors in compilation time. Besides, if the API changes and we have a lot of calls, there is no way to rebuild the calls quickly.
Is there a better way to build the call to avoid this kind of problems? I mean, like we do with Web Services, for instance.
Like Nkosi mentioned, that is how it is designed. However you could create a class with the API URI's and use those instead of literals
public class ApiUris
{
public const string Products = "api/products";
public const string Services = "api/services";
public const string Orders = "api/orders";
/* ... */
}
That way you can easily change the path if your webapi changes.
Even Web Service and WCF service does not gurantee build fail if the server changes the URL or type and/or structure of the parameter. You come to know about the changes only when you call the service and it breaks.
In case of calling Web APIs surely there is no way you can figure out that the URL or the paramemeter is incorrect until you call the API.
At the same time, Web API are not built to be changed frequently. If they are not reliable no one would use them. So if you are using an API you can be sure that they will not change their URL or stop supporting certain input parameters overnight making their consumer applications like yours break. They surely woudn't want to be sued by their customers.
Any API would change gradually and with well advanced notice to their customers so that they get time to change their implementation to support new version of API.
So you can rely on the service which you are using and puting values related to it (such as URLs) in the config file would be good enough. Or you can choose to put API Urls in database so that when it changes you just need to update entry in the database and changes will be effective immediately.
Just extending upon Adam's solution you can get a List of your routes using
System.Web.Routing.RouteTable.Routes.ToList();
Then getting the path depends on the concrete implementation of the RouteBase abstract class.

MVC Web Api as a middle tier service

In our recent application we are planning to use MVC Web API as a Middler tier service. Meaning, front end will access the WebAPI middler tier service to get all the data it required from DB and to update the data back to DB. Along with this there may be many other methods that we will need. For example check whether user already exists in the system, Validate the address, etc. Now I have come into a point that my webapiconfig.cs routing is becoming more complex. For example my UserController in WebApi project will have following methods.
public User Get(int userId)
{
}
public bool IsUserExists(string username)
{
}
public bool UpdateUser([FromBody]User user)
{
}
public bool ChangePassword(string username, string password)
{
}
To manage all of these I may need so many routing configurations in webapiconfig.cs. I am not sure how to deal with these when other controllers comes to the picture. Should I use AttributeRouting? Any suggestion highly appreciated. Thanks.
If you have the option to use web api 2 go for attribute routing. You can save your lot of development effort in configuring routes.
Also make sure you are following resource based routing design and REST principles, than old RPC style routes. i.e for basic CRUD operations :-
Create - HTTP POST to /user
Read - HTTP GET to /user or /user/{id}
Update - HTTP PUT to /user
Delete - HTTP DELETE to /user/{id}
For example for updating an user
Instead of route /user/UpdateUser
You should do a
HTTPPUT to /user/
For more tips on REST check this.

Demerit of using MVC Controllers for Web API's

In our application, which is Single Page application, we are using MVC controller(Action methods as API) for CRUD operation's. Which I feel its wrong.
Can someone tell me if its correct?
Eg:-
I have an API Controller say :-
public class MockAPIController : ApiController
{
// GET api/MockAPI/5
public ClassA GetSomething(int id)
{
return new ClassA();
}
}
and this can be called from client-side using /api/MockAPI/GetSomething/1. Similarly if I create MVC Controller like:-
public class MockAPIController : Controller
{
// GET api/MockAPI/5
public ActionResult GetSomething(int id)
{
return new JsonResult(new ClassA(),JsonRequestBehavior.AllowGet);
}
}
Still, I can get it work. Can some-one tell me whats demerit of using MVC controller for API?
EDIT:-
Is it recommended to use MVC Controller for API methods?? If Not, then can someone point out the -ve aspect of it?
Using the web API you can return objects as normal and your clients can specify the content-type.
This will automatically serialize the objects to xml or json without the need to specify a new action just to change the return type.
So your API call will always remain as:
public ClassA GetSomething(int id)
{
return new ClassA();
}
But it is capable of returning xml and json without any changes in the controller.
Web API provides cleaner way to craft your HTTP responses. It is extremely extensible, testable and faithful to the HTTP spec.
Web API was NEVER intended to provide an "out-of-the-box" REST framework.
MVC is a HTTP framework, optimized for serving content to a Web Browser. Web API has no bias as to what client is using it.
As per my understanding,
MVC controllers are extended over API Controller. You can do almost
everything what can be done with API Controller.
(People please correct me if I am wrong, its purely my understanding which I am sharing!)
Now, if your application is a web based application/internet or intranet where you have very few api call's then you can stick with MVC Controllers. Only care that need to be taken care is sending data as JsonResult(basically serializing`to JSON or whatever). If you have more funda of SPA, the API controllers is what you need.
I myself have not found much articles stating a strong line separating what to use when, it's always a developers pain to decide and implement.
It's less about merit and demerit of using ApiControllers in place of Controllers, and more about implementation and usage.
ApiControllers are specifically meant for building REST-ful Apis which return serialized data to the client in simplest form.
And, using controllers you can return Views, Different Types of ActionResults in different form. You can definitely convert the type of data you are returning, like the way you are using here but it's not the same with ApiControllers.

Categories

Resources