0

I am very new to routing in ASP.NET Core.

The system I am prototyping has strings with associated names like:

  • /dev/accounting/people = "people string"
  • /test/it/documents = "some it document string"
  • /some/arbitrary/name/separated/by/slashes = "some other string"

much like a dictionary. What I want is to make an endpoint in my API that would be accessed like:

  • http://mysite/api/GetString/dev/accounting/people
  • http://mysite/api/GetString/test/it/documents
  • http://mysite/api/GetString/some/arbitrary/name/separated/by/slashes

I have this so far

Dictionary<string, string> _stringDictionary = new Dictionary<string, string>()
{
    { "/abc", "this works" },
    { "/abc/def", "this doesn't" },
    { "/abc/def/ghi", "neither does this" },
    { "/some/arbitrary/name/separated/by/slashes", "nor this"},
};

[Route("api/GetString/{objectPath}")]
[HttpOptions]
[HttpGet]
public IActionResult GetString(string objectPath)
{
    // -http://mysite/api/GetString/abc this works
    // -http://mysite/api/GetString/abc?param1=2&param2=3 this does too
    // -http://mysite/api/GetString/abc/def nope
    // -http://mysite/api/GetString/some/arbitrary/name/separated/by/slashes?param1=2&param2=3 nope
    // I want objectPath to be everything after 'getstring' in the URLs above EXCEPT the parameters

    string resultValue = "[[NOT FOUND]]";

    if (_stringDictionary.ContainsKey(objectPath))
        resultValue = _stringDictionary[objectPath];

    return new OkObjectResult(new 
                              { 
                                  result = resultValue,
                              });
}

Obviously, this is a routing problem. I have been able to get one or two parameters in the GetString method to work, but I get 404's when specifying more. Clearly I'm doing something wrong, and it may very well be that what I am asking for is impossible.

1 Answer 1

1

https://asp.mvc-tutorial.com/routing/routing-templates/

The solution turned out to be to use a '*' character in front of the token, like this:

[Route("api/GetString/{*objectPath}")]

I don't get the leading slash, but that's fine, I can prepend that before the search. Of course, after 3 hours of searching, I find this 17 minutes after posting the question :-)

Best regards and HTH someone

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.