Azure Health Check end point code changes ASP NET - c#

I need to add code to ASP NET Restful Api to enable Azure Health Check. Most resources I found are about Net Core. I am looking for reference and advice on how to add the code changes in Asp Net Restful Api code base.

Azure Health Check needs a path that it can ping to monitor the availability of your app. That path is just an endpoint you have defined. .Net Core / .Net has built-in support for creating health endpoints, see the docs and for .Net Framework you could use a lib like this one.
In its most basic form you can create one like this
public class HealthController : ApiController
{
[HttpGet]
[AllowAnonymous]
public IHttpActionResult GetHealth()
{
return Ok(new { Status = "Healthy" });
}
}
Key takeaway: there is nothing magic about a health endpoint. You can create the most simple one or an advanced one that also checks dependencies like databases etc.As long as the endpoint returns status code between 200-299 the instance will be considered healthy.

Related

How to look up information based Azure AD User in ASP.NET Core MVC App

I use Azure Authentication in ASP.NET Core MVC and would like to lookup information based on this and use it in the whole app.
Edit:
What I basically want can be described as follows:
Users logs in with Azure Auth
The app extracts the preferred_username
An object is created that uses preferred_username to look up more information from the database
this object can be used for DI in order to
create IAuthorizationRequirement in order to use [Authorize(Policy = ("IsRequirementBasedOnLookedUpInformation"))]
can be uses in the views, for example to hide html code in razor like this #if (Object.IsRequirementBasedOnLookedUpInformation)
End Edit
Authentication is set up like this:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureB2C"));
This allows me to use the ClaimsPrincipal User throughout the whole application.
Now I want to look up some information in a database and make it available for the whole app.
public class UserWithPhoneNummer (dbContext _dbc, ClaimsPrincipal cp)
{
// do stuff with cp.Identity.Name aso
}
Then I would like to inject it via DI in a controller like this
public CashFlowAnalysisController(dbContext _dbc, UserWithPhoneNummer _uwpn)
{
dbc = _dbc;
uwpn = _uwpn;
}
I've found plenty of tutorials and guides, but these all aim at scenarios with EF Core and sophisticated user management.
When I try the IUserClaimsPrincipalFactory I get an error:
services.AddScoped<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<mvcUser>,UserClaimsPrincipalFactory>();
Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Mvc.Models.mvcUser]' while attempting to activate 'Mvc.Authorization.UserClaimsPrincipalFactory'.
I am happy to share more code, if needed and would be grateful for any pointers on how to achieve this.

How to fetch data from a third party API in ASP.NET Core 6 Web API

I am currently trying to make a request to a third party library in my ASP.NET Core 6 Web API and work with this data (it really has to run over a Web API template).
That means I'm importing data from another API.
Unfortunately I don't know how to tell my application to make a call.
I would have expected the Task to run automatically when the application starts. Unfortunately this is not the case.
I first wanted to test whether this works at all when the application is started. Later, I would build in a scheduler, which sends requests accordingly.
It should be possible, right?
It would be great if someone could tell me as well if it's possible to put the URL "localhost:xxx/" in the constructor somehow, but still not get any dependency injection errors with AddScoped.
I use Flurl.Http to make Http Requests.
If it is important. My program.cs is in a console application and DataImport in an empty project
Unfortunately, I am relatively new to the ASP.NET world and I hope that the question is not too unprofessional. Otherwise I apologize. It's kind of hard to google for a problem like this and find something
using Flurl;
using Flurl.Http;
public class DataImport
{
private readonly Service service;
public DataImport(Servie service)
{
_service = service;
}
public async Task<IEnumerable<Data>> ImportData()
{
var data = await "localhost:xxx/".AppendPathSegment("data").GetJsonAsync<DataDto[]>();
return _service.Add(data.Select(it => new DatoDtoToData(it)));
}
}
program.cs:
builder
.Services
... Service Injections
....
.AddScoped<DataImport>()
I would encourage you to look into Azure Functions.
Have a look at Microsoft's Introduction to Azure Functions. In the Scenarios section we can read.
The following are a common, but by no means exhaustive, set of scenarios for Azure Functions.
If you want to...
then...
Build a web API
Implement an endpoint for your web applications using the HTTP trigger
...
Build a serverless workflow
Chain a series of functions together using durable functions
...
Run scheduled tasks
Execute code on pre-defined timed intervals
...
I really think this could work well for you because:
You can run/host it locally or host it in Azure.
It's very easy to start with. Microsoft's tutorials are:
Quickstart: Create your first C# function in Azure using Visual Studio, and
Quickstart: Create a C# function in Azure using Visual Studio Code
It supports multiple ways of triggering your functions. There are over 20 tiggers; with 2 of the most relevant for you should be:
Azure Functions HTTP trigger
Timer trigger for Azure Functions

Health check, ASP.NET Web API

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.

How to create an attribute that serve as a Web API?

I am working on a project that we need to shift the responsibility of authorization level to the separated Web API.
What is important creating an attribute class in Web API which able to check some policies. What we want is adding the Web API reference to other projects and check these policies by adding AuthPolicyAttribute above actions and controllers. By adding this attribute, Web API check accessibility by getting the action name and user name.
For example (This is one of the actions in a project that need to call Web API by AuthPolicy attribute):
[AuthPolicy]
public IActionResult GetTypes([FromBody]Input input)
{
// Code
}
I've searched a lot but unfortunately, I haven't found any example.

Is it possible for ASP.NET MVC website (not project) to return HttpResponseMessage

I am creating a RESTful webservice using ASP.NET MVC (not ASP.NET Web API). What I want to do is have every method in the controller return their result based on an input parameter (i.e. json or xml).
If I were using ASP.NET Web API, the HttpResponseMessage works for this purpose. When I attempt to return an HttpResponseMessage from a controller in ASP.NET MVC, there is no detail.
I have read that in this approach, I am supposed to use ActionResult. If I do this, then I need to create an XmlResult that inherits from ActionResult since it is not supported.
My question is why HttpResponseMessage does not work the same in both situations. I understand that in Web API, we inherit from ApiController and in ASP.NET MVC we inherit from System.Web.Mvc.Controller.
Any help is greatly appreciated.
Thanks,
EDIT 1
Much thanks to Fals for his input. My problem was in how to create an empty website and add all of the necessary functionality in. The solution was to use Nuget to get the packages mentioned in the comments and then to follow the steps in How to integrate asp.net mvc to Web Site Project.
Web Api is a Framework to develop Restfull services, based on HTTP. This framework was separeted into another assembly System.Web.Http, so you can host it everywhere, not only in IIS. Web API works directly with HTTP Request / Response, then every controller inherit from IHttpController.
Getting Started with ASP.NET Web API
MVC has It's implementation on System.Web.Mvc. coupled with the ASP.NET Framework, then you must use It inside an Web Application. Every MVC controller inherits from IController that makes an abstraction layer between you and the real HttpRequest.
You can still access the request using HttpContext.Response directly in your MVC controller, or as you said, inheriting a new ActionResult to do the job, for example:
public class NotFoundActionResult : ActionResult
{
private string _viewName;
public NotFoundActionResult()
{
}
public NotFoundActionResult(string viewName)
{
_viewName = viewName;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 404;
context.HttpContext.Response.TrySkipIisCustomErrors = true;
new ViewResult { ViewName = string.IsNullOrEmpty(_viewName) ? "Error" : _viewName}.ExecuteResult(context);
}
}
This ActionResult has the meaning of respond thought HTTP Error.
As a matter of fact, it is indeed possible. You basically have two options:
develop your custom ActionResult types, which can be an heavy-lifting work and also quite hard to mantain.
add WebAPI support to your website.
I suggest you to do the latter, so you will have the best of two worlds. To do that, you should do the following:
Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
Add one or more ApiControllers to your /Controllers/ folder.
Add a WebApiConfig.cs file to your /App_Config/ folder where you can define your Web API routing scheme and also register that class within Global.asax.cs (or Startup.cs) file.
The whole procedure is fully explained here: the various steps, together with their pros-cons and various alternatives you can take depending on your specific scenario, are documented in this post on my blog.

Categories

Resources