3

My problem comes when I call a webapi2 GET with a string parameter that has special char (with normal character all works correctly).

AngularJs

this.getByContactValue = function (contactValue) {   
        return $http.get("/api/subjects/"+ contactValue+ "/ContactValue" );
    }

c#

[Route("api/subjects/{contactValue}/ContactValue")]
public IEnumerable<Subject> GetByContactValue(string contactValue)
{
    return repository.GetByContactValue(contactValue);
}

The response is 404 error. I tried also to modify the request in this way

this.getByContactValue = function (contactValue) {
        var request = $http({
            method: "get",
            url: "/api/subjects/ContactValue", //modified the route in c# controller
            data: contactValue
        });
        return request;
    }

But the error is the same.

Which is the best way to call the webapi?

lpernice
  • 115
  • 1
  • 3
  • 12
  • The best way is to pass the parameters in either querystring or the form. can you please provide the data for which the error is occuring? – SamGhatak Apr 06 '16 at 13:08
  • Possible duplicate of http://stackoverflow.com/questions/14359305/mvc-web-api-routing-fails-when-url-contains-encoded-ampersand – Federico Dipuma Apr 06 '16 at 19:38

3 Answers3

4

You've to pass data in query strings as

$http({
    url: "/api/subjects/ContactValue", 
    method: "GET",
    params: {contactValue: contactValue}
 });

Update your action

[Route("api/subjects/ContactValue?contactValue={contactValue}")]
public IEnumerable<Subject> GetByContactValue(string contactValue)
{
    return repository.GetByContactValue(contactValue);
}
M.S.
  • 4,283
  • 1
  • 19
  • 42
  • 2
    In this way i receive this error - `The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.` Have I to specify the value of the parameter in the controller ? – lpernice Apr 07 '16 at 10:36
2

Finally I solved in this way

[Route("api/subjects/ContactValue")]
public IEnumerable<Subject> GetByContactValue([FromUri]string contactValue)
{                                 
    return repository.GetByContactValue(contactValue);
}
lpernice
  • 115
  • 1
  • 3
  • 12
0

Simplest way is to use encodeURI or encodeURIComponent, it'll Encode data in url.

Ts-

   let bg= encodeURIComponent(contactValue);
   return AuthAxios.get(`${APINAME}?bg=${bg}`);

API

    [HttpGet(nameof(GetBgList))]
    public async Task<IActionResult> GetBgList(string bg)
    {
        return Ok(MessageAlert.DataFound(await _bgService.GetBgList(bg)));
    }
panky sharma
  • 2,029
  • 28
  • 45