Azure - This Service is unhealthy .NET Backend - c#

I have constructed an API using webapi2.2.
When I deploy the API to Azure I get the Service Unhealthy Message...when I check the logs of my API the log gives the error message
"Boot strapping failed: executing 'WebApiConfig.Register' caused an
exception: 'Parameter count mismatch.'.
The Application Start function is below
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
And my WebApiConfig.cs has the following:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Formatters.JsonFormatter.
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));.......
Another question here: The api implements its own Security mechanism (I used the following as a reference http://bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/). Would this implementation work in Azure or would you have to make use of the x-zumo header authorisation mechanism?

I found the resolution to this - I believe that the problem is caused by the fact that I have another mobile services app running in my Azure account. That app was built awhile ago - early 2015 and used the register procedure with no parameters
public static void Register(){.....}
I think that this may have confused the service operation (the fact that one app has a register without parameters and the other has a register with one parameter). To resolve the issue with my new app I removed the config parameter, and build the config settings in the register function see below
public static void Register()
{
ConfigOptions options = new ConfigOptions();
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
config.EnableCors();.....
Remember though you will need access to the using Microsoft.WindowsAzure.Mobile.Service namespace...this can be obtained by installing the nuget package WindowsAzure.MobileServices.Backend
Hope this helps someone who has similar problems

Related

Is Azure storage supported in Azure Static Web App functions?

I'm working on an API for an Azure Static Web App. The web app is implemented in Angular (although that isn't important for this question), and the API is implemented in C# (NET 6). Deployment to Azure is via a GitHub action.
I can create an HTTP trigger API endpoint that works fine, like so:
public static class Tester
{
[FunctionName("Tester")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/tester")] HttpRequest req,
ILogger log)
{
return new OkObjectResult("Hello World");
}
}
I'm also able to access this directly via the SWA URL: https://<sitename>.azurestaticapps.net/api/v1/tester.
However, as soon as I add a reference to an Azure storage NuGet package to the project file (specifically Microsoft.Azure.WebJobs.Extensions.Storage.Blobs), making no other changes to the code, the API endpoint no longer works once deployed (although it will work locally).
On deploying the code with that package referenced in the .csproj, hitting the API endpoint gives a 503 status code with the response:
Function host is not running.
I enabled Application Insights for this static web app, and a CryptographicException is being thrown on startup:
An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. For more information go to http://aka.ms/dataprotectionwarning Could not find any recognizable digits.
(The link in the message doesn't go anywhere useful).
I'm presuming this has something to do with the AzureWebJobsStorage setting, which cannot be set in an Azure Static Web App (for whatever reason).
Based on all of the above, it would seem that using Azure storage from within a static web app C# function is verboten. However, I can't find that stated explicitly online anywhere. Has anybody got this kind of thing to work?
I removed the following nuget packages to make it working:
Microsoft.Azure.EventGrid
Microsoft.Azure.WebJobs.Extensions.EventGrid
I decomposed my http functions to a separate project because SWA does not support the EventTriggers right now.

How can I set up a middleware in a .NET Core 3.1 Azure Functions project? trying to dependency inject an external service that requires middleware

As the title says,
How can I set up a middleware in a .NET Core 3.1 Azure Functions project? trying to dependency inject an external service that requires middleware.
First off, there are some problems here.
The Function app you create in Visual Studio 19, doesn't contain a Startup.cs class.
So we have to create this manually. Then there's a problem that it's not behaving like a real Startup class. It needs to inherit FunctionsStartup.
This is achieved by adding this line of code before the namespace first for some reason.
[assembly: FunctionsStartup(typeof(test_project.Startup))]
Then we need to inherit FunctionsStartup and then implement it.
public override void Configure(IFunctionsHostBuilder builder)
{
}
So after this, we are able to Add stuff like Singleton or external service like so,
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSomeExternalService();
builder.Services.AddSingleton<SomeOtherStuff>(
new SomeOtherStuff(config, env_SomeOtherStuff));
}
But now my real problem starts. We need to add middleware for some functionality to work in the external service.
Usually, you can do this in a web applications (not function app) like so,
public void Configure(IApplicationBuilder app)
{
app.UseSomeExternalServiceMiddleware();
}
The problem is, I can't figure out how to do this in a function app with core 3.1
maybe it's not implemented the same way, I don't know why.
Is there a workaround for this sort of problem?
There is no direct way to do this but there is a proposed feature that you can refer to.
More References :
Dependency Injection in Azure Functions with C# (twilio.com)
c# - Azure Functions Runtime v3 Middleware - Stack Overflow
Be able to overwrite http response in IFunctionsWorkerMiddleware · Issue #530 · Azure/azure-functions-dotnet-worker · GitHub

Why does the DatabaseInitializer get called twice?

I’ve inherited an MVC that currently does some setup work with the ApplicationStart method so that when the application comes back to life with an IIS Application pool this setup has already been carried out.
As pseudo-code:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Build Api autofac container
// Build MVC autofac container
// Resolve serviceOne from the MVC container
var serviceOne = (IServiceOne)DependencyResolver.Current.GetService(typeof(IServiceOne));
// Make setup call - includes external http calls and DbContext checking
serviceOne.syncToExternal();
// Resolve serviceTwo again from the MVC container
var serviceTwo = (IServiceTwo)DependencyResolver.Current.GetService(typeof(IServiceTwo));
// Make setup call - publishes application information to internal message queues so that we know it's running
serviceTwo.syncToInternalSystems();
}
}
In the ApplicationStart I run through the normal process of setting up Autofac containers; one for the MVC and one for the WebApi. In here the respective MVC or Api controllers, service classes and my DbContext are registered.
The setup work in the ApplicationStart needs a service and a DbContext which I resolve from the MvcContainer, as the WebApi one is not accessible at this point.
ServiceOne retrieves data from an external url and using this to seed / check the current contents of the database.
ServiceTwo reads back some of this data and publishes it to internal message queues within the company.
Once the Application_Start() has finished and the Home page has loaded: if I make a request which routes through the MVC then the DbCobntext's registered databaseInitialzer does not get called as it was run during the Application_Start, but if I make an /api request the databaseInitializer does get called.
I suspect that running the setup in ApplicationStart method is preventing a flag being set in the System.Data.Entity.Database which managed the Connection; hence when the DbContext is resolved from the Api Container it thinks the database hasn’t been initialised...?
Any help would be much appreciated.
My fallback will be to shift all of the setup into a seed method which runs when the databaseInitialiser/Migration is called; but it would be useful to know why the original version of the code was failing to execute as expected.
the ApplicationStart run every time the ApplicationPool starts, no matter what. You have to use another mechanism to populate your DB. Like Migrations.

Why do I get the error "The service type ITraceWriter is not supported." from Azure?

I am trying to get my Web API 2 up and running on an Azure App Service. It works fine on my machine, on IIS 10, with the following tracing added, from the package Microsoft.AspNet.WebApi.Tracing:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableSystemDiagnosticsTracing();
SystemDiagnosticsTraceWriter traceWriter = config.EnableSystemDiagnosticsTracing();
traceWriter.IsVerbose = true;
traceWriter.MinimumLevel = TraceLevel.Debug;
config.Services.Add(typeof(ITraceWriter), new TextFileTracer());
This works fine on my dev machine, but I get the error
The service type ITraceWriter is not supported.
as soon as I publish to Azure. I thought a modern ASP.NET app was supposed to be self contained, and not rely on services being present or configured on the host, and a very up to date host at that. Why is this happening?
According to your description, I tested your code on my Web API application and I got the server error as follows on my local side.
The service type ITraceWriter is not supported.
Parameter name: serviceType
As mentioned in this official document about setting the Trace Writer:
To enable tracing, you must configure Web API to use your ITraceWriter implementation. You do this through the HttpConfiguration object, as shown in the following code:
config.Services.Replace(typeof(ITraceWriter), new TextFileTracer());
Only one trace writer can be active. By default, Web API sets a "no-op" tracer that does nothing. (The "no-op" tracer exists so that tracing code does not have to check whether the trace writer is null before writing a trace.)
After replacing ITraceWriter service with the TextFileTracer instance, I could make it work as expected both on my side and Azure.

ServiceStack.UseCases self hosting failure

I am trying to take the github ServiceStack.UseCases/ImageResizer project, and make it self hosted. I thought this would be really easy, so I referenced this: https://github.com/ServiceStack/ServiceStack/wiki/Self-hosting but AppSelfHostBase is undefined in the project. I then tried AppHostHttpListenerBase and that got me to the point where I could at least hope to setup my self host:
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("Image Resizer", typeof(AppHost).Assembly) {}
public override void Configure(Container container) {}
}
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
AppHost appHost = new AppHost();
appHost.Init();
appHost.Start("http://*:1301/");
}
}
I then transferred the project over to my CentOS box with mono. In monodevelop I was able to build and run, but it failed during runtime. It appears it still thinks it is an Mvc or Asp.Net project.
Aside from this attempt, I have a working self hosted ServiceStack project running there, but it is not this ImageResizer and all attempts to get my existing project to include the new project have also failed.
I also tried to include code that was part of the working self hosted project into the new one, but then symbols are undefined. Basic symbols like "ServiceStackHost". If I start trying to use Nuget and do more "Install-Package" I can solve this symbol problem, but then just cause other symbols that used to be resolved to no longer work. I don't really fully understand Nuget. Any ideas for a way forward would be appreciated.
ServiceStackHost and AppSelfHostBase are new classes added in ServiceStack v4.
You can use AppHostHttpListenerBase which is a Self-hosting class in ServiceStack v3. You're looking at the v4 docs, here are the docs for ServiceStack v3 which for Self-Hosting is at:
https://github.com/ServiceStackV3/ServiceStackV3/wiki/Self-hosting
Self-Hosting apps are normally created in a Console Application where-as your example is trying to run a self-hosting app inside an ASP.NET Web Application. If you want to run ServiceStack in an ASP.NET app you should inherit AppHostBase, otherwise if you want to run a self-hosting application, create a new Console Application and inherit from AppHostHttpListenerBase.

Categories