Return of Webapi Dynamic types

Asked

Viewed 288 times

0

I am writing a method in Webapi that returns the type Httpresponsemessage.

I have an appointment that returns a type Dynamic that would return the query of the data as it is different information.

In the return of the data an error occurs but Visual Studio complained of problems in the code. However I noticed something curious

Visual Studio error message

Error CS1973 'Httprequestmessage' has no applicable method named 'Createresponse' but appears to have an Extension method by that name. Extension methods cannot 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:

Permitted

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 Api.Query() returns an object of the type Dynamic

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

  • What do you mean by "Not allowed"? Is there a build error? Is there a runtime error? What is the error? What is the signature of the Api method.?

  • Hi @Gabrielferrarini really owed the error message, I added in the text. Thanks

1 answer

1


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

However, the generic parameter allows the use of Anonymous Types which 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 anonymous object initialization syntax, and is then a child object of a "nameless" class known only to the compiler when compiling. And if it’s an object then it’s accepted as an argument by Generic Type Parameter.

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

In the second section, the type variable 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 parameter Generic Type Parameter does not accept a variable dynamic as argument, by definition. A solution would be to cast the "return" variable, as suggested by the compiler.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.