Error consuming WebApi and testing it on localhost

0

I have a WebApi, where I make a query to Sql Server, in other controllers there is no problem, it is done correctly, but in this I skip the following error

  

An error has occurred.   Multiple actions were found that match the request: Get on type   WebApiFacturador.Controllers.ConexionController DatosEmpresa on type   WebApiFacturador.Controllers.ConexionController   System.InvalidOperationException    in   System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction (HttpControllerContext   controllerContext) in   System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction (HttpControllerContext   controllerContext) in   System.Web.Http.ApiController.ExecuteAsync (HttpControllerContext   controllerContext, CancellationToken cancellationToken) in   System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext ()    

This is my code

    using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiFacturador.Datos;

namespace WebApiFacturador.Controllers
{
    public class ConexionController : ApiController
    {
        // GET: api/Conexion
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Conexion/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Conexion
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/Conexion/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Conexion/5
        public void Delete(int id)
        {
        }
        SqlConnection miConexion = new SqlConnection("data source = snare.arvixe.com; initial catalog=****; user id=****; password=****");
        [HttpPost, HttpGet]
        public string DatosEmpresa(int idempresa)
        {
            try
            {
                if (miConexion.State == ConnectionState.Closed)
                {
                    miConexion.Open();
                }
                SqlCommand comando = new SqlCommand("SELECT idEmpresa, [Status], Empresa, RFC, svrFacturador, usrFacturador, bddFacturador, pwdFacturador, cuantosFolios, comunFac, llave FROM logins where idEmpresa = '" + idempresa + "'", miConexion);
                comando.ExecuteNonQuery();
                Conexion datos = new Datos.Conexion();
                DataSet ds = new DataSet();
                List<Conexion> LstRazon = new List<Datos.Conexion>();
                SqlDataAdapter da = new SqlDataAdapter(comando);
                da.Fill(ds, "logins");
                //da.Fill(ds, "CrmCustomersEmails");
                //Data Row llenarlo con el data set 
                DataRow DR;
                DR = ds.Tables["logins"].Rows[0];
                //Si el usuario existe, extrae sus datos
                if ((idempresa == int.Parse(DR["idEmpresa"].ToString())))
                {
                    SqlDataReader reader = comando.ExecuteReader();
                    if (reader.Read())
                    {
                        //Traer los datos del usuario logueado
                        datos.Status = int.Parse(reader["Status"].ToString());
                        datos.Empresa = reader["Empresa"].ToString();
                        datos.RFC = reader["RFC"].ToString();
                        datos.svrFacturador = (reader["svrFacturador"].ToString());
                        datos.usrFacturador = (reader["usrFacturador"].ToString());
                        datos.bddFacturador = (reader["bddFacturador"].ToString());
                        datos.CuantosFolios = int.Parse(reader["cuantosFolios"].ToString());
                        datos.ComunFac = (reader["comunFac"].ToString());
                        datos.IdEmpresa = int.Parse(reader["idEmpresa"].ToString());
                        datos.llave = Guid.Parse((reader["llave"].ToString()));
                        LstRazon.Add(datos);
                    }
                    miConexion.Close();
                    var JsonLogin = JsonConvert.SerializeObject(LstRazon);
                    return JsonLogin;
                }
                else
                {
                    miConexion.Close();
                    return null;
                }
            }
            catch (Exception ex)
            {
                miConexion.Close();
                return "Error" + ex.Message;
            }
        }
    }
}

and this one my RouteConfig file

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "api/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
    
asked by Oscar Navarro 25.10.2017 в 01:19
source

1 answer

1

I advise you to put a [RoutePrefix ("Api / NameController")] on top of your public class NameControllerName: ApiController so you know that in each request to that controller the default route will always be "localhost: TuPuerto / Api / NombreDelController" + "TuMetodo"

When you are going to receive a data in your Get method you usually always receive FromUri Example: "localhost: YourPort / Api / ControlName" + "YourMethod? parameter = value" and when it is a Post method [FromBody] (I'll leave it for homework)

You can also add another fragment to the path you set by default to the controller's start by adding [Route ("Fragment")] over your method Example: "localhost: TuPuerto / Api / ControlName "+" Fragment? Parameter = value " this to avoid that the real name of your method is not exposed as such

You should use only one verb per method in your controller so that you do not have problems and you could separate the logic from your main method so that you can identify the errors that you have and use an object of type HttpResponseMessage to generate a more elaborate response of your services

If you can not reach the service with the "localhost: TuPuerto / Api / TuController / TuMetodo? parameter = value" you could try removing the word "Api" from the url since sometimes when creating the project and not using the [RoutePrefix ("")] defaults to "/ TuController / TuMethod? parameter = value"

I leave you something that could help with routes and best practices link

    
answered by 25.10.2017 / 04:51
source