How can I call a Web API method from an MVC controller action method?
This is what I am trying, this is my controller method:
public ActionResult ProductDetail(long id)
{
using (var client = new HttpClient())
{
var productDetailUrl = Url.RouteUrl(
"DefaultApi",
new { httproute = "", controller = "ProductDetails", id = id },
Request.Url.Scheme
);
var model = client
.GetAsync(productDetailUrl)
.Result
.Content.ReadAsAsync<ProductItems>().Result;
return View(model);
}
}
My Web API method:
private ProductEntities products = new ProductEntities();
public IEnumerable<ProductItems> GetProductDetail(int ID)
{
var produc = products.ExecuteStoreQuery<ProductItems>(
"GetProductDetail @ProductID ",
new SqlParameter("@ProductID", ID));
return produc;
}
When I am doing this I am getting an error @ var model
in my MVC action method after returning the data, saying:
"
Newtonsoft.Json.JsonSerializationException
: Cannot deserialize JSON array "(i.e.[1,2,3]
) into type 'ProductDetails.Models.ProductItems
'. The deserialized type must be an array or implement a collection interface likeIEnumerable
,ICollection
orIList
. To force JSON arrays to deserialize add theJsonArrayAttribute
to the type. Line 1, position 1."
Can anyone help me do this, suggest another better method, or correct me if I am doing it wrong anywhere? I have to show the returned data in my view, the data should be returned to my controller.