Return type dynamic WebApi

0

I'm writing a WebApi method that returns the HttpResponseMessage type.

I have a query that returns a dynamic type that would return the query for the data because it is different information.

The return of the data ends up with an error, but Visual Studio complained about problems with the code. But I noticed something curious

Error message in Visual Studio

  

Error CS1973 'HttpRequestMessage' has no applicable method named   'CreateResponse' but appears to have an extension method by that name.   Extension methods can not be dynamically dispatched. Consider casting   the dynamic arguments or calling the extension method without the   extension method syntax.

If I put the code in the following format:

Allowed

var retorno = new { cupons =  Api.Consultar(codigo) };
return Request.CreateResponse(HttpStatusCode.OK, retorno);

Not allowed

var retorno = Api.Consultar(codigo);
return Request.CreateResponse(HttpStatusCode.OK, retorno);

Assume that Api.Consult () returns an object of type dynamic

What is the difference between these two codes where one is accepted and another is not?

    
asked by anonymous 08.06.2017 / 20:41

1 answer

1

The signature of the Request.CreateResponse method uses Generic Type Parameter that does not, by design, allow passage of a dynamic (untyped variable), that is the compiler does not know its type (class) during compilation, only at runtime.

However, the generic parameter allows you to use Anonymous Types that are, as the name says, unnamed types (classes) with their "names" known only to the compiler during compilation.

In the first section, the variable is initialized via the initialization syntax of anonymous objects, and then a child object of an "unnamed" class known only to the compiler when compiling. And if it is an object then it is accepted as an argument by Generic Type Parameter .

var retorno = new { cupons =  Api.Consultar(codigo) };
return Request.CreateResponse(HttpStatusCode.OK, retorno);

In the second snippet, the variable of type var ( Implicit typed local variable) gets a dynamic , which would be the same as having declared the variable to be dynamic . When compiling, the error occurs because a Generic Type Parameter parameter does not accept a dynamic variable as an argument, by definition. One solution would be to cast the variable "return" as suggested by the compiler.

var retorno = Api.Consultar(codigo);
return Request.CreateResponse(HttpStatusCode.OK, retorno);
    
09.06.2017 / 08:15