0

I want to pass values using model as parameter. This is basically the mvc web api app

This is my Model class

public class ConversionModel
{
    public double  value { get; set; }
    public int qty { get; set; }
    public double  result { get; set; }
    public string  from { get; set; }
    public string  to { get; set; }
}

This is My controller code

[HttpGet]
[Route("api/Conversion/Currency")]
public double Currency(ConversionModel c)
{
    return c.value;
}

And my url is

http://localhost:5267/api/Conversion/Currency?value=123

But is showing me an error

Object reference not set to an instance of an object.

Ahmed
  • 25
  • 7

2 Answers2

0

You are only providing an integer value, it cannot be converted to ConversionModel.

You can either use post

[HttpPost] 
public double Currency([FromBody]ConversionModel c)

which is more suitable for a complex object.

Or pass the values as separate get parameters, constructing a ConversionModel in the method body.

Or use get with [FromUri]; this still requires supplying all the individual parameter-values. (see here)

Passing a collection of individual values is a little fragile/clumsy, I would prefer to use post. Besides which, it is unlikely that you need all the values, and an instance of the class, if you will be simply returning a double value, so post is most likely to be appropriate.

Andy G
  • 19,232
  • 5
  • 47
  • 69
0

You cannot pass an object in query string. You need to write all parameters in your Route annotation.

[Route("api/Conversion/Currency/{value}/{qty}/{result}/{from}/{to}")]

And then in your action:

public double Currency(double value, int qty, double result, string from, string to) {
    var conversionModel = new ConversionModel();
    conversionModel.value = value;
    conversionModel.qty = qty;
    conversionModel.result = result;
    conversionModel.from = from;
    conversionModel.to = to;

    // Rest of your code.
}
Anis Alibegić
  • 2,941
  • 3
  • 13
  • 28