Best way to use database connection for every get/post request in .net core web api service - database

I have .net core web api service. Should i open new connection and close for every get/post request? Or, is there a performance way to use db connection like a global connection variable?

Yes. You use the AddDbContext extension method to configure your DbContext and it'll automatically create a Scoped instance of the context which is created and disposed with each request:
var connection = #"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<BloggingContext>
(options => options.UseSqlServer(connection));
For a full example visit: https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db?tabs=visual-studio

Related

Sveltekit: Sharing service objects (e.g. configured http client) across pages

I am moving my app from Svelte SPA (original) to Sveltekit multi page app (new).
In the original app, I configure a http client up top and put it context using:
setContext(HTTP_CLIENT, httpClient)
Now the entire app can get that http client using
const httpClient = getContext(HTTP_CLIENT)
I do this because my app can be started with debug parameters than turn on http request logging.
I'm not clear how to do similar in Sveltekit, because it seems that pages do not share a context.
I tried sticking the http client in the session like this:
import { session } from "$app/stores";
$session.httpClient = httpClient
and I got:
Error: Failed to serialize session data: Cannot stringify arbitrary non-POJOs
So $session is meant to be serialized, ok. Does that mean that I need to put whatever debug parameters a user supplied in $session, and each page needs to freshly instantiate its own http client? Or is there some other idiomatic sveltekit way of doing this?
PS I know sveltekit has its own fetch so you might want to say "don't use your own http client", but my app uses many different service objects (graphql client for example) that can be configured in debug (and other) modes, so please don't zero in on the fact that my example is a http client.
One way around this could be to send down the configuration in the top __layout file, create the http client there and store in a store. Since stores are shared across all pages the client can then freely use this store.

How to use camel consul component for agent API?

As per camel documentation for consul(camel.apache.org/consul-component.html), the supported HTTP API are kv, event and agent. There are example of kv (key/value store) which are working fine but there is no such example for agent API. I went thruogh the documentation of Consul [www.consul.io/docs/agent/http/agent.html] and the corresponding java client [github.com/OrbitzWorldwide/consul-client] as well and tried to figure out how consul:agent component should work but I have found nothing simple there.
main.getCamelTemplate().sendBodyAndHeader(
"consul:agent?url=http://localhost:8500/v1/agent/service/register",
payload,
ConsulConstants.CONSUL_ACTION, ConsulAgentActions.AGENT); //also tried with ConsulAgentActions.SERVICES, but no luck
I also checked the test cases mention at https://github.com/apache/camel/tree/master/components/camel-consul/src/test/java/org/apache/camel/component/consul but unable to find anything related to agent api.
So my question is that how to use consul:agent component.
UPDATE: I tried the below code and able to get the services.
Object res = main.getCamelTemplate().requestBodyAndHeader("consul:agent", "", ConsulConstants.CONSUL_ACTION, ConsulAgentActions.SERVICES);
It seems that the consul component only work for the GET operation of the HTTP agent API. But in that case how do I register a new service (like /v1/agent/service/register : Registers a new local service) with consul component?
This code works for me:
ImmutableService service =
ImmutableService.builder()
.id("service-1")
.service("service")
.addTags("camel", "service-call")
.address("127.0.0.1")
.port(9011)
.build();
ImmutableCatalogRegistration registration =
ImmutableCatalogRegistration.builder()
.datacenter("dc1")
.node("node1")
.address("127.0.0.1")
.service(service)
.build();
ProducerTemplate template = main.getCamelTemplate();
Object res = template.requestBodyAndHeader("consul:catalog", registration, ConsulConstants.CONSUL_ACTION, ConsulCatalogActions.REGISTER);
But it's looking some inelegantly (like workaround), and i think there are other solutions.
One can use
.to("consul:agent?action=SERVICES")
to retrieve the registered Services as Map<String, Service>, with service id as map key.
And
.to("consul:catalog?action=REGISTER")
to write registrations, expecting an ImmutableCatalogRegistration as body
Note that you can employ a CamelServiceRegistrationRoutePolicy to register Camel routes as services automatically.

Restful API without database connection

My current project is a restful API that connects to a database to retrieve data.
What should be done if the route handlers can't access the database? In such a case I would implement a middleware that sends back a global response that indicates that the API is temporarily not available.
Which status code should be returned? Internal Server Error (500) or Service Unavailable (503)?
Is it efficient if the middleware checks with each request the database connection?
Well normal people dont understand 500 or 503 . so its better to catch these exceptions in catch block and then set some appropriate message .
Also for all your database related question explore database connection use connection pooling lib such as HakariCp

How to get client certificate inside web method at asp.net web forms c#?

I configure IIS to get certificates from client. And I can easily get client certificate inside event handler, for example Page_Load
HttpClientCertificate cert = Request.ClientCertificate;
Now I need to create web method what will get client name from certificate and return data for this client. But how can I get client certificate inside static web method where I don't have access to Request?
In any method, including in a static method, you can use HttpContext.Current. If this is non-null, then you can access the Request property. If that is non-null, then you can access the ClientCertificate property.
Of course, it may be null...

Does a WCF service with basicHttpBinding create a new connection for each request?

I have a Silverlight client calling a WCF Service on an IIS web server. It uses the default basicHttpBinding setting for the calls. My client code has the usual Visual Studio generated proxy that is generated when using the 'Update Service Reference' menu option.
Does every call to the service using that proxy use the same connection? Or does it create a connection each time a call is made and then close it down once the reply is received? As the client is actually making a SOAP call over HTTP I just assumed that every service request had a new connection created but I want to check if that is the case?
(I need to know because if it creates a new connection each time then each request could end up at a different server because there are several servers being load balanced. It is uses a single connection for the duration of the proxy then I can assume they all end up at the same machine and so cache state information for better performance.)
You have to differ between connection and session. Connection allows you calling the server. Session allows you maintaining state among subsequent requests from the same client. Application session for example allows using server side caching. First of all BasicHttpBinding does not support session.
HTTP 1.1 specification describes that each connection should be opened as persistant. When you call first HTTP request to a new server, a persistant connection is established and it remains opened for subsequent calls to the same server. If you do not call the server again it is closed after some timeout. Persistant connection openning and closing is handled internally and it is fully transparent to developers.
Persistant connections are used by all browsers and HTTP APIs including .NET HttpWebRequest and so all HTTP based bindings. You can demand that new connection is created and closed for each request/response by creating custom binding with HTTP transport channel and property KeepAliveEnabled set to false. It will add additional overhead because new TCP connection will be established for each request/response. Establishing TCP connection is time consuming operation.
Persistant HTTP connection is not related to WCF application session. WCF session is by default handled between single service proxy instance and single service instance. All subsequent calls from the same proxy instance are handled by the same service instance (PerSession instancing). WCF application session is built on top of any other session - connection, security, reliable. BasicHttpBinding does not support any of these session types so it can't use WCF application session (and PerSession instancing). Each request for service exposed on BasicHttpBinding is by default handled by new service instance (PerCall instancing).
By HTTP specification the client should be able to open only two concurrent persistant HTTP connections to the same server. Persitant HTTP connections are shared for all service proxies calling the same server from the same client machine in the same period of time. Moreover single proxy instance can call the service from many different connections if long period of time elapses among calls. Those are reason why persistant HTTP connection can't be used as connection session. HTTP is not connection oriented - it only allows reusing connection for performance reasons.
The inactivity timeout of persistant HTTP connection in WCF is 100 seconds. I have found this timeout by measuring in Procmon. I have unanswered question about setting this timeout to different value.
When you are using load balancing you can't also rely on connection. The persistant HTTP connection is opened between client and load balancer. But it is responsibility of the load balancing algoritm to select processing server. In case of BasicHttpBinding it can be simple Round Robin because processing servers will not use any kind of session. In case of session oriented binding you have to use some algoritm with session affinity (sticky sessions) which will forward all requests from the same session to the same server so the same service instance can handle them. But it is not the case of BasicHttpBinding.

Resources