Search code examples
signalr.clientasp.net-core-signalr

How to call SignalR Hub Method that has Enum parameters with a Javascript Client?


Using a C# signalR client is straight forward, and it works; but I am stuck with a JS client.

 public async Task MyHubMethod(string userName, CityEnum city, FruitEnum fruit) {
    //etc.
 }
 
public enum CityEnum
{
    LONDON,
    LISBON,
    RIO,
    SYDNEY
}

public enum FruitEnum
{
    APPLES,
    BANANAS,
    ORANGES
}

//C# Client, YAY it works !
    string userName = "mindi-mink";
    CityEnum city = CityEnum.LONDON;
    FruitEnum fruit = FruitEnum.APPLES;
    await _connection.InvokeAsync("MyHubMethod", userName, city, fruit);
    

//Javascript Client:
    ???

Not sure what to do, other than changing the server method to take string parameters, and convert them back to Enums server-side;

How to do it from the Javascript signalR client? (without changing the server method signature).


Solution

  • Enum values are integers, surely passing integers should work?

    Yes, just tested and it does work!

    Define objects to match your Server-side enums

    const CityEnum = {
        LONDON : 101,
        LISBON : 102,
        RIO : 103,
        SYDNEY : 104,
    }
    
    const FruitEnum = {
        APPLES     : 0,
        BANANAS    : 1,
        ORANGES    : 2,
    }
    
    //JS-Client:
    const userName = "mind-mink";
    const city = CityEnum.LONDON;
    const fruit = FruitEnum.APPLES;
    
    await _hubCnn.invoke("MyHubMethod", userName, city, fruit);