0
  • Language used: C#

  • Input: An abbreviation or an emoticon.

  • Output: Translation of the abbreviation or emoticon

  • Code:

    public class EmoticonController : ApiController { // GET: api/emoticon/abbreviation/shortform [HttpGet] [Route("api/emoticon/abbreviation/{shortform}")]

     public string Abbreviation(string ShortForm)
    {
         string outputMessage;
    
         // Switch case that assigns the outputMessage the translation to the abbreviation entered by the user 
         switch (ShortForm)
         {
    
             case "TY":
                 outputMessage = "Thank you";
                 break;
    
             case "(~.~)":
                 outputMessage = "sleepy";
                 break;
    
             default:
                 outputMessage = "Invalid Input";
                 break;
         }
    
         return outputMessage;
     }
    

}

I run the above code in Visual studio and enter the URL as

localhost/api/emoticon/abbreviation/(~.~)

and I get the following error: C# URL Special characters error

PS: The screenshot URL does differ from the code and that I have mentioned. Please ignore that. I fixed it but the error still persisted.

  • In the screenshot the requested url is different – Vivek Nuna Oct 09 '21 at 18:36
  • Allowed characters in URIs are limited. If you need to use special characters (as you do) you should encode them. See https://stackoverflow.com/questions/1856785/characters-allowed-in-a-url, https://stackoverflow.com/questions/575440/url-encoding-using-c-sharp, https://stackoverflow.com/questions/44920875/url-encode-and-decode-in-asp-net-core – Christoph Lütjen Oct 09 '21 at 18:50

1 Answers1

1

Since you have the action header "...abbreviation/{shortform}" you need a MVC style Url with route valulues. This Url is very sensitive to a special characters. You can try to encode/decode the special characters, but it is not always succesfull and sometimes it is not possible. It is much easier to use a query string as a part of URL. You can achieve it by changing your action header to this

[Route("~/api/emoticon/abbreviation")]
 public string Abbreviation(string ShortForm)

and after this you can use this url

localhost/api/emoticon/abbreviation?shortForm=(~.~)
Serge
  • 40,935
  • 4
  • 18
  • 45