Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass decimal as value in WebAPI 2 URL

I am creating a Web Api (v2.0) Method that needs to take in a decimal value as its parameter.

I am getting a 404 not found error if I use the following URL:

http://localhost:4627/api/Product/Eligibility/10.5

But it works if I use the following URL against an Int parameter:

Http://localhost:4627/api/Product/Eligibility/10

These are the two corresponding Methods in the api:

// GET api/Product/Eligibility/10.0
[Route("api/Product/Eligibility/{amount:decimal}")]
public decimal GetEligibiilty(decimal amount)
{
    return amount;
}

// GET api/Product/Eligibility/10
[Route("api/Product/Eligibility/{amount:int}")]
public decimal GetEligibiilty(int amount)
{
    return amount;
}

Steve

like image 472
samneric Avatar asked Feb 21 '14 20:02

samneric


People also ask

How do you pass decimal value in URL?

Had a similar problem with passing a decimal in the URL, anyone using ASP.NET web pages here is a solution when redirecting after a transaction and the variable amount has a decimal in it: Response. Redirect(@Href("~/Thankyou", amount + "/")); The slash at the end of the URL is required to get it working.

Why to use FromBody in Web API?

Using [FromBody] Here is an example client request. When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).


2 Answers

Got it working by adding a "/" to the end of the URL!

http://localhost:4627/api/Product/Eligibility/10.5/

Will find this method:

// GET api/Product/Eligibility/10.5/
[Route("api/Product/Eligibility/{amount:decimal}/")]
public decimal GetEligibiilty(decimal amount)
{
    return amount;
}

Steve

like image 88
samneric Avatar answered Sep 22 '22 17:09

samneric


I recently had this problem while working with Web API in Visual Studio 2015. I solved the problem by adding ?parameterName=decimalValue at the end of the URL. In your case could be something similar to this:

http://localhost:4627/api/Product/Eligibility?amount=10.5

I hope can help.

like image 36
Joseph L. Avatar answered Sep 21 '22 17:09

Joseph L.