Home > database >  Accepting special characters as input from the URL in C#
Accepting special characters as input from the URL in C#

Time:10-12

  • 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

CodePudding user response:

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=(~.~)
  • Related