Sending data to a Web Api

1

I'm doing a system with Entity Framework and Web Api. It has happened to me that I can only pass an object to the Api, I can not send a string, this why is it? Where do you configure that you only receive one object? and not only that, that the object has to be of a defined class, I do not know if it is understood, that's how it works for me.

[HttpPost]
[Route("Get")]
public L_Persona Get(L_Persona in_obj)
{
    L_CabeceraUbicacion a = L_Persona.get(in_obj);
    return a;
}

But that's not how it works for me:

[HttpPost]
[Route("Get")]
public L_Persona Get(int id)
{
    L_Persona a = L_Persona.get(id);
    return a;
}

If I have to pass a id , for it to work I have to pass a person object with the id and the other empty fields, when the id could pass directly. It also happens to me that I want to send an image and I get an error too, something like that

  

415 unsupported media type

How do I configure then that the Api Web receives what I want to pass to it and not always an object?

    
asked by Lucho 08.05.2017 в 14:49
source

3 answers

1

The type of content you want to send must be specified in the request, the most frequent are JSON and XML:

  • For JSON it is Content-Type: application/json
  • For XML it is Content-Type: text/xml , or in your case Content-Type: application/xml

To configure the parameters to be received in the Api it must be in App_Start\WebApiConfig.cs where by default it is assigned:

config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
);

When consuming the route, you must follow the structure:

https://{url base}/api/{controller}/{id}

Similarly, in that file, you can define custom routes.

    
answered by 08.05.2017 в 17:36
1

Complementing the excellent response of colleague Flxtr , you should only specify in Route that you will receive an id:

[Route("Get/{id}")]
public L_Persona Get(int id)
{
     //Código
}

Greetings!

    
answered by 08.05.2017 в 19:06
1

to pass a string from the client you can use a query string in the URL, of course the url depends on the configuration of your routing, but the query string at the end does not change:

link

a real example:

 [HttpGet]
    [Route("get_modulos_by_rfc/")]
    public IHttpActionResult get_modulos_by_rfc(string rfc, string softwareCode)
    {}

on the client

 WebRequest request = WebRequest.Create("http://localhost/api/empresa/get_modulos_by_rfc/?rfc=" + rfc + "&softwareCode=" + softwareCode);
    
answered by 25.10.2017 в 01:52