WillCore.Requests 0.8.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package WillCore.Requests --version 0.8.1
NuGet\Install-Package WillCore.Requests -Version 0.8.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="WillCore.Requests" Version="0.8.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add WillCore.Requests --version 0.8.1
#r "nuget: WillCore.Requests, 0.8.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install WillCore.Requests as a Cake Addin
#addin nuget:?package=WillCore.Requests&version=0.8.1

// Install WillCore.Requests as a Cake Tool
#tool nuget:?package=WillCore.Requests&version=0.8.1

WillCore.Requests

If you have a .NET core WebAPI project and if you are tired of typing out AJAX request after request, WillCore.Requests is the framework that will brighten your day.

It is like adding a WCF service reference to your JavaScript. But for WebAPI.


Features

  • Supports either REST or RPC.
  • Simple initialization.
  • Uses reflection to generate JavaScript methods, parameters and results to mirror your WebAPI controllers. These methods can then be used to make requests to the service.
  • Full Visual Studio intellisense support via docx comments.
  • Outputs either:
    • ES5
      • A single file containing all the functions for each controller, action, paramter class and result class.
      • Uses a simple polyfill for promises and XMLXHR requests under the hood.
    • ES6
      • Classes that are exported as ES6 modules are generated.
      • Uses FetchAPI under the hood.
  • With full IOC, the API can easily be extended or functionality can be changed.

Supported Platforms

WillCore.Requests is only tested with .Net Core 2.2.

Getting Started

NuGet package coming soon. For now download the solution, build it and reference the projects.

To enable the JS code generation add the following line in the Configure method in the Startup.cs file:

app.GenerateJSContext<ControllerBase>(new JSClassContainer<ControllerBase>());

If your controller inherit from Controller use the following line:

app.GenerateJSContext<ControllerBase>(new JSClassContainer<Controller>());

When you run your solution, the JavaScript files will be generated in the \js folder inside your solution.

Excluding Controllers From The Code Generation

Sometimes a controller has to be excluded from the code generation (like MVC controllers that return views, or APIs not available for public access).

To exclude a controller, simply add a ExcludeFromAPIContract attribute to the controller.

[ExcludeFromAPIContract]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
}

Consuming The Service

ES6 Mode (default mode)

WillCore.Requests builds ES6 modules for each controller. These modules can simply be imported and used. The file name the module is contained in, is the same name as the controller. The request container is name controllerName + "RequestContainer".

To import a request container for PersonController:

import { PersonRequestContainer } from "./js/Person.js";

The request container is a class, to create an instance of the class, call the constructor with the base URL of your service:

 let personRequests = new PersonRequestContainer("http://localhost:53964");

You can now call the actions on your service by simply invoking methods on the request container instance:

Rest
//Import the request container for controller : PersonController
import { PersonRequestContainer } from "./js/Person.js";

//In order to use await, we need an async function.
(async () => {
    //Creates an instance of the request container.
    let personRequests = new PersonRequestContainer("http://localhost:53964");
    //Calls a get method to get all the people
    var allPeople = await personRequests.Get();
    //Gets a single person
    var singlePerson = await personRequests.GetById(2);
    //Updates a record
    singlePerson.name = "My Name Is Bieber..whahaaha";
    await personRequests.PutById(8, singlePerson);
})();
RPC
//Import the request container for controller : RPCController
import { RPCRequestContainer } from "./js/RPC.js";

//In order to use await, we need an async function.
(async () => {
    //Creates an instance of the request container.
    let personRequests = new RPCRequestContainer("http://localhost:53964");
    //Calls a get method to get all the instances
    var allPeople = await personRequests.GetAllPersons();
    //Gets a single person
    var singlePerson = await personRequests.GetPerson(6);
    //Updates a record
    singlePerson.name = "My Name Is Bieber..whahaaha";
    await personRequests.UpdateReceipt(8, singlePerson);
})();

ES5 Mode

Some people are living in the past and are still using Internet Explorer. Unfortunately there are cases where we have to cater for those poor souls and ignore the awesomeness of ES6 and later versions of JavaScript.

To enable ES5 mode, change the line in your Startup.cs from and to the following:

//From
app.GenerateJSContext<ControllerBase>(new JSClassContainer<Controller>());

//To
var jsCodeBuilder = new JSClassContainer<ControllerBase>();
jsCodeBuilder.Configuration.ESMode = ESMode.ES5;
app.GenerateJSContext<ControllerBase>(jsCodeBuilder);

A file (requestContext.js) will be generated in the js folder of your solution. If the folder does not exist, it will be created. Simply import the file and start using it.

ES5 mode uses a polyfill for ES6 promises. The "then" function can be used as a callback when the request is done executing.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>Test</h1>
    
    <script src="js/requestContext.js"></script>
    <script>
        //Create a new instance of the request container
        var personRequests = new PersonRequestContainer("http://localhost:53964");
        //Use promises on the requests
        personRequests.Get().then(function (people) {
            console.log(people[0]);
            personRequests.PutById(8, people[0]).then(function (result) {
                console.log(result);
            });
            personRequests.Post(people[0]);
            personRequests.DeleteById(2);
        });
    </script>
</body>
</html>

Submitting Complex Models

Models or complex types can be submitted via POST or PUT requests with full intellisense support.

In order to submit a model, first import the model from the same file the request context is imported from: (The models are named the same as the C# models used as the action's parameters)

import { PersonRequestContainer, Person, Receipt } from "./js/Person.js";

An instance of the model has to be submitted:

//Create a person with 2 receipts
var person = new Person(50, "John", "Foe", new Date(), null,
    [
        new Receipt(30, 60, "Some receipt"),
        new Receipt(31, 10, "A new receipt")
    ]);
//Creates the person
var postResult = await personRequests.Post(person);
//Updates the person
var putResult = await personRequests.PutById(50, person);

Specifying HTTP Request Headers

HTTP request headers such as authentication tokens can be specified globally. Headers are set on a request container instance, however they apply globally for all future requests across all request containers.

The headers can be configured via the setHttpHeaders method on a request container:

let personRequests = new RPCRequestContainer("http://localhost:53964");
personRequests.setHttpHeaders({ AuthToken: "The Token Value" })
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.2 is compatible.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETCoreApp 2.2

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.9.0 549 9/2/2019
0.8.4 507 8/28/2019
0.8.3 476 8/28/2019
0.8.2 497 8/27/2019
0.8.1 489 8/27/2019
0.8.0 470 8/27/2019

Initial release, Alpha version