web api call with checking part of the URL using UriTemplate not working correctly

423 Views Asked by At

Perhaps I do not understand how to properly use the UriTemplate

I always want to search the incoming url for

api/whatever      // that is it 

If URL is like below, I want to ONLY get api/CheckMainVerified So I suppose without using UriTemplate, I guess a substring check or regex would work ?

http://localhost:29001/api/CheckMainVerified/223128

This is what I was doing

var url = "http://localhost:29001/api/CheckMainVerified/223128";


//var host = new Uri(serverHost.AbsoluteUri);
var host = new Uri("http://localhost:29001");

var apiTemplate = new UriTemplate("{api}/{*params}", true);

var match = apiTemplate.Match(host, new Uri(url));

var finalSearch = match.BoundVariables["api"];
string parameters = match.BoundVariables["params"];

finalSearch.Dump();
parameters.Dump();
match.Dump();
1

There are 1 best solutions below

0
Luke On BEST ANSWER

I think you're just missing 2nd option in the template (see example below).

var template = new UriTemplate("{api}/{controller}/{*params}", true);
var fullUri = new Uri("http://localhost:29001/api/CheckMainVerified/223128");
var prefix = new Uri("http://localhost:29001");
var results = template.Match(prefix, fullUri);

if (results != null)
{
    foreach (string item in results.BoundVariables.Keys)
    {
        Console.WriteLine($"Key: {item}, Value: {results.BoundVariables[item]}");
        // PRODUCES:
        // Key: API, Value: api
        // Key: CONTROLLER, Value: CheckMainVerified
        // Key: PARAMS, Value: 223128
    }

    Console.WriteLine($"{results.BoundVariables["api"]}/{results.BoundVariables["controller"]}");
    // PRODUCES:
    // api/CheckMainVerified
}

As such, adding the "{controller}" to the template should resolve your issue. From there, you could do a simple string comparison. i.e.

if ($"{results.BoundVariables["api"]}/{results.BoundVariables["controller"]}" == "api/CheckMainVerified") { ... }

Alternatively, as you suggested; you could use a substring or regex solution.