Server running on Windows 10 as a service, OWIN self-hosted with WebAPI endpoints making an SSL connection without configuring a private key

I have created a prototype application the runs on Windows 10 that communicates with a server (described in the title) running as a service on a different system and successfully got SSL working but I’m missing something because I never seemed to generate any keys. I only just self-taught myself how to use PowerShell to create the self-signed certificate (so bare with me) using New-SelfSignedCertificate but I have very little insight into why this worked at all. From my very limited understanding a private key on the server is absolutely required for SSL to work, and I never associated one with my certificate… but it’s working and I think I’m fooling myself.

All I did was create the certificate with New-SelfSignedCertificate -Subject "CN=My Server Name"
Then add the binding with netsh http add sslcert certhash=<the thumbprint> appid={the app id}
And add the reservation for the service with netsh http add urlacl url="https://+:<my port number>/" user='NT AUTHORITYLocalService'

This all works, but I’m not sure I understand how because I never configured a private key. I know it must need to be expanded upon somehow to make it more secure because every single tutorial out there talks about making the certificate trustworthy and assigning a private key to the cert… but I’ve done none of that and it still appears to work. Granted, the client is not a web browser and will never care about the authenticity of the server because of the context in which this particular application will run (It’s to connect scientific components together in a lab, and there’s almost no exposure outside the network).

What am I missing here? Did Windows 10 provide a private key anyway? How can it really be encrypted if I didn’t need to specify these things? I also never moved the certificate to a trusted store of any kind because it frankly didn’t seem necessary since the client is just a proprietary front-end application.

c# – How to use single child Unity container for OWIN middleware and WebAPI

I am using OWIN to self host WebAPI service. There is Unity to serve as IoC container. Within several OWIN middlewares (e.g. authorization layer) as well as in WebAPI I need to access unity container to resolve my dependencies. There should be single child container per each request so that there is for example single DB context which is used several times during the request and it is disposed at the end of request along with unity container. For WebAPI I would like to use same container as for previous middlewares. However, default UnityHierarchicalDependencyResolver creates its own child container from given parent per each request. So that I had to write my own infrastructure to force WebAPI to use existing child container. Please review the following code snippets. I would be happy for any kind of feedback since this is quite critical part of my application.

Here is my app configuration method:

public static void Configure(IAppBuilder app, IUnityContainer container)
{
    //register middleware that creates child container for each request
    app.UseUnityContainer(container);

    //register other middlewares ...
    
    //create httpconfig
    var config = new HttpConfiguration
    {
        DependencyResolver = container.Resolve<OwinUnityDependencyResolver>()
    };

    //...

    config.MessageHandlers.Insert(0, container.Resolve<OwinDependencyScopeHandler>());

    app.UseWebApi(config);
}

This is UseUnityContainer extension method that is responsible for creating and disposing child containers:

public static void UseUnityContainer(this IAppBuilder app, IUnityContainer container)
{
    app.Use<UnityMiddleware>(container);
}

private class UnityMiddleware : OwinMiddleware
{
    private readonly IUnityContainer _parent;

    public UnityMiddleware(OwinMiddleware next, IUnityContainer parent) : base(next)
    {
        _parent = parent;
    }

    public override async Task Invoke(IOwinContext context)
    {
        using (var child = _parent.CreateChildContainer())
        {
            context.SetUnityContainer(child);
            await Next.Invoke(context);
        }
    }
}

To access and store container within the OWIN context there are following extension methods:

public static class UnityOwinContextExtensions
{
    private const string UnityContainerKey = "OwinUnityContainer";

    public static IUnityContainer GetUnityContainer(this IOwinContext context)
    {
        return context.Get<IUnityContainer>(UnityContainerKey);
    }

    public static void SetUnityContainer(this IOwinContext context, IUnityContainer container)
    {
        context.Set(UnityContainerKey, container);
    }
}

OwinUnityDependencyResolver class used in HttpConfiguration:

public class OwinUnityDependencyResolver : IDependencyResolver
{
    private static readonly IDependencyScope NullScope = new NullDependencyScope();

    private readonly IUnityContainer _parent;

    public OwinUnityDependencyResolver(IUnityContainer parent)
    {
        _parent = parent;
    }

    public void Dispose()
    {
        //parent container is disposed in SureStowWebApiService
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return _parent.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _parent.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IDependencyScope BeginScope()
    {
        //BeginScope should not be called as there should be already scope registered by OwinDependencyScopeHandler
        return NullScope;
    }

    private class NullDependencyScope : IDependencyScope
    {
        public void Dispose()
        {
        }

        public object GetService(Type serviceType) => null;

        public IEnumerable<object> GetServices(Type serviceType) => null;
    }
}

OwinDependencyScopeHandler class that is used to retrieve existing child container from OWIN context and create new dependency scope out of it. This handler is registered in HttpConfiguration.

public class OwinDependencyScopeHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var context = request.GetOwinContext();
        var scope = new OwinUnityDependencyScope(context);

        //this prevents HttpRequestMessageExtensions.GetDependencyScope to initialize scope from dependency resolver
        request.Properties(HttpPropertyKeys.DependencyScope) = scope;

        return base.SendAsync(request, cancellationToken);
    }
    
    private class OwinUnityDependencyScope : IDependencyScope
    {
        private readonly IUnityContainer _container;

        public OwinUnityDependencyScope(IOwinContext owinContext)
        {
            _container = owinContext.GetUnityContainer(); //this is child container created by UnityMiddleware
        }
        
        public void Dispose()
        {
            //_container should be disposed by UnityMiddleware
        }

        public object GetService(Type serviceType) => _container.Resolve(serviceType);

        public IEnumerable<object> GetServices(Type serviceType) => _container.ResolveAll(serviceType);
    }
}

webapi – Angular no ejecuta el servicio tipado para invocar una api

estoy realizando un aplicación en Angular 9 que se conecta a una API.NET; he realizado pruebas con otros métodos y funcionan correctamente,pero sucede algo bastante extraño cuando mi componente llama un método del servicio buscaClienteB(): string o al indicar ‘buscaClienteB(): miclase’. No alcanza a ejecutarlo y no manda ningún error.
El html del componente: el evento que interesa es keyup de mi input text verificacliente()

    <div class="card-container listado">
    <ul>
        <li class="lst" *ngFor="let plan of planes" >{{plan.nombre}}</li>
    </ul>
    Periodo de: <input type="text" value="60" (keyup)="mandaDias(dias.value)" #dias /> dias &nbsp;&nbsp;Su id Cliente:<input type="text" value="1" (keyup)="verificacliente(txtid.value)" #txtid />
    <input type="button" (click)="mandaDias(dias.value)" (routerLink)="('/contratos')" name="btnAdquirir" disabled value="Tu vida está en riesgo" #asegurabtn> &nbsp;&nbsp;<input type="button" enabled value="Cancelar"  (click)="resetActivo(asegurabtn)" #cancelabtn>
</div>

El typescript de componente:

   constructor(private renderer: Renderer2,public listaplanes:ServicePlanesService,public apiseguro:WcfserviceService) {
    this.planes = (
      { nombre: "PLAN A", id: 1 },
      { nombre: "PLAN B", id: 2 },
      { nombre: "PALN C", id: 3 },
     .........
      { nombre: "PLAN L", id: 9 }
    )
  }
verificacliente(_id){
  //this.listaplanes.buscaclient(_id);
  this.apiseguro.buscaClienteB;//<- Esta es la invocación que me interesa
  console.log('se llamó api buscaClienteB');//<- Esto siempre escribe en consola
}

El codigo del servicioAngular:

 buscaClienteB(): string {//<-     
    let observ = this._http.get(`${this.url3}?id=7`);
    //return this._http.get<cliente>(`${this.url3}?id=${_idcliente}`);//Este metodo lo invocaba antes desde otro servicio pero el resultado q devolvía undefined
    console.log('urlpeticion:'+this.url3);
    let oCliente: cliente;
    observ.subscribe(resp => {
      console.log(resp);
      oCliente.Apellidos = resp.toString();
    })
    
    console.log('oCliente.Apellidos:'+oCliente.Apellidos);
    console.log(' --wcfservice; metodoB terminado');
    return oCliente.Apellidos;
  }

Adjunto link en video para detalles: http://srecorder.com/s/9phq
no recibo error en consola

website – Console based webAPI access

Here’s an over simplification of our integration system – we need to fetch orders, put them in some files to be picked up by another system, then acknowledge those orders (its like notifying – yes we’ve got them) and finally when the other system has processed them and they’re queued for shipping – we’ll get some files in a pickup folder (say one file per order) which need to be POSTed to an external cloud system.

Now, imagine diff web-stores like Shopify, Walmart, Amazon, … of
course each has their own process. They all talk in webAPIs so at one
end we’ve JSON based webAPI transactions (GET, POST, PUT, …) and at
the other end we’ve file system and scheduler based tools (our end of
the system).

  • Our system/tools are good at receiving the JSON webAPI response and producing JSON request payloads.
  • However, they fall a bit short when it comes to interacting with modern webAPIs (header, token, OAuth, …). So, batch script + CURL was our immediate choice to complete the integration.

Going ahead, we’re in the RESTful webAPI ear and now we need to establish asynchronous processes (i.e. fetch orders, wait until we get them and then acknowledge them .. a typical webAPI interaction). Also, need to share authentication mechanism, like periodic OAuth token renewal, … well this is where the Batch script + CURL seem to be limited by their design (they’re not meant for programming).

No doubt CURL is a wonderful tool but, now we need a better console app based approach, so here’re a few options we see –

  1. CURL + Advance batch sripting (or even powershell).
  2. vbScript/JScript was a choice but it’s becoming extinct.
  3. node.js (emrging tech so has a learning curve).
  4. C# Core console app (we’ve experience with .NET)
  5. ASP.NET might be a great choice for cloud solution but for now our system has console access. So, its for future I believe.

Kindly suggest your opinion, apparently diff options will suide diff needs but we want to invest on a path for longterm. Its about creating an eco-system of webAPI vs file system based interactions & scheduling in an environment based on asynchronous interaction.

Answer – Magento 2 handles WEBAPI errors and success with multiple data entries

I have the following input data for my custom web API:

"data":({"sku":"BM0011","warehouse":"kklm","qty":"5"},{"sku":"YU9982","warehouse":"cvxs","qty":"2"})

I need to validate the data and run the inventory update function and catch an error if it exists. Since this contains multiple data that I need to process, if there is a data validation error, the next data will be processed without stopping the entire process. I am currently doing it like this:

/**
 * {@inheritdoc}
 */
public function updateProductsInventory($data)
{
  $errors = array();
  $success = array();
  $results = array();

  foreach ($data as $productData) {
    $errValdation = $this->validateUpdateInventory($productData);
    if (!empty($errValdation)) {
      $errors('validation')($productData('sku')) = $errValdation;
      continue;
    }
    try {
      $result = $this->updateInventory($data);
    } catch (Exception $e) {
      $errors('insert')($productData('sku')) = __("There's something wrong, please try again!");
    }
  }
  if (!empty($errors)) {
    $results('errors') = $errors;
    if (empty($success)) {
      throw new MagentoFrameworkWebapiException($results);
    }
  }
  if (!empty($success)) $results('success') = $errors;
  return $results;
}

public function validateProductInventory($data){
    $errors = array();
    $mandatories = array('sku','qty','warehouse');
    foreach ($mandatories as $mandatory) {
      if (!array_key_exists($mandatory,$data)) {
        $errors() =   $mandatory . ' ' . __("is Empty");
        continue;
      }elseif(empty($data($mandatory))) {
        $errors() =   $mandatory . ' ' . __("is Empty");
        continue;
      }
      if ($mandatory == 'Inventory') {
        if ($data($mandatory) < 0) {
          $errors() = __("Inventory must be Greater or equal to 0");
        }
      }
    }
  }

I don't know if this is the right way to return an API result, and I don't think this is very neat. Is there a recommendation to improve my web API result?

What is the simplest version of the best practice application architecture for a backend in C # and ASP.NET Core WebAPI?

I know that in some contexts DDD, CQRS and EventSourcing are the best course of action, but in my case this would be too complicated for two reasons:

  • My team is a beginner and we want them to be productive as early as possible
  • It's really easy to use, but obviously the complexity can increase over time

This question is an attempt to reformulate this question: what is a simple implementation of the onion architecture for C # ASP.NET Core WebAPI and SQL db that is not fully DDD and CQRS?

My previous thoughts are:

  • Using onions or neat architecture is better than the old n-tier model and not difficult to learn. This makes it easier to test the domain entity level
  • The API should not return data as objects of the domain entities, but should be assigned to separate view models

I'm not sure whether to design the database and SQLs manually and then use Dapper or use something like EntityFramework Core code first.

I wonder if CQRS would be a good idea without DDD.

I would also like to say a little about our simple application. It is intended for an amusement park where seasonal workers in various departments have to undergo some training. You should be able to register for a course, cancel your registration, and the instructor in charge of the course should be able to mark your registration with participation and approval. There are also some reports that read and display all of this data. This is version 1.

Version 2 is an admin dashboard for registering users as trainers and administrators (who can view all reports). Administrators should also be able to map which departments need which training.

Perhaps many will consider this to be opinion-based, but I believe that it should be possible to define a few broad steps in a tutorial about the application architecture, and although the exact order may be controversial, I expect some kind of consensus on which steps to take should be considered. So that's my question; What specific topics / learning steps are there in this context in the application architecture about simple layering, n-tier and onion / clean – and under CQRS, DDD EventSourcing?

magento2 – Saves only one field from the REST webapi

Okay, I just do not get it.

It will try to save only the title of webapi's existing CMS page, but if I do, all other fields will be set to null.

I use postman:

PUT URL: http://dcm2.carsonscreens.com.au/rest/all/V1/cmsPage/19

Body Content:

{"page":
    {
        "id":"19",
        "title": "My Title"
    }
}

This saves the title, but also leaves the content and other fields blank.

Is there a way to save / update only one title (or only one field)?

Sharepoint Online / 365 integration (uploading files) in the React app, which is hosted on Azure and WebApi C # .Net Core 2.2

I've been having trouble interacting / automating a way to upload files from a Web application created in React and upload files to a Sharepoint online site in a particular folder for several weeks. The WebApp is hosted in Azure and uses a C # .Net Core 2.2 as the backend.

I'm trying to use a kind of REST API to help me with this task. (May be activated in the frontend or in C # Core or C # MS FW .Net for the backend.)
I'm looking for a way to do this on the internet, but all tests have failed.

Anyone can give me insights, tips or advice on how to do this?

I'm trying:

  • Use code from Microsoft WebPage (Using jQuery).

  • When using PnP, but on my local host, a CORS issue is displayed (I am trying to interact with the client ID and the secret ID with Sharepoint).

ASP.Net Core WebAPI authorization policy for users or administrators

I have a controller that returns data about users. I want to set the authorization so that an administrator can access this controller and retrieve data for each user, and a non-admin user can retrieve the controller and data for themselves.

I excluded with (Authorize (Roles = "Admin")) This means that users can not receive their own data. So I added the following logic to the controller action:

var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
var roles = _httpContextAccessor.HttpContext.User.FindAll(ClaimTypes.Role);

var query = roles.Select(r => r.Value).Contains("Admin");

Customer customer =await _context.Customers.FindAsync(id);

if (!(customer.EmailAddress == userId || query))
 return Unauthorized();

This roughly corresponds to the stack overflow response, but it does not apply to MVC, but to ASP.Net Core.

My question is, is there any way to do this with an authorization policy? Adding the RequireRole exam is straightforward and covered in the MS documentation and in many blogs. However, I could not find a way to use a policy to verify that the data that the user wants to access is their own.

I'm sure this is not an unusual requirement, is there any way to do it, or is what I'm doing okay? The only other approach I could think of was to have two separate endpoints, but both options do not seem relevant.

primaverabss – SPRING V.10 WebAPI – Add Special Line

I'm trying to add a comment line to a WebAPI sales receipt.

Similar to what I already did in .NET Motor.Vendas.Documentos.AdicionaLinhaEspecial(ObjDocVenda, BasBE100.BasBETiposGcp.vdTipoLinhaEspecial.vdLinha_Comentario, , "Teste");

I assume that the same thing is to do about WebAPI through a call {{apiUrl}}Vendas/Docs/AdicionaLinhaEspecial/1//Teste with the following request text (POST):{
"TipoDoc": "FA",
"NumDoc": "5",
"Entidade": "0001",
"TipoEntidade": "C",
"Serie": "2019"
}

The parameter "1" in the URL refers to the corresponding value of ENUM from BasBE100.BasBETtypesGcp.vdTypeLineSpecial, Since this is a comment line, the second parameter (PrecUnit) becomes empty and the third parameter is the comment.

Explains what I'm doing, the result is the following error:

{"Message": "An error has occurred.",
"ExceptionMessage": "Can't bind multiple parameters ('clsDoc' and 'TipoLinha') to the request's content.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   em System.Web.Http.Controllers (…) }

What am I doing wrong?