Anil Kumar
Anil Kumar

Reputation: 303

How to call a user define method in webapi

I am developing wepapi service.Below is my code.

[ActionName("getdata")]
[HttpGet]
public string getdata(string Phoneno, int servicetypeID)
{

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con2"].ConnectionString);
    string SQL = " EXEC [dbo].[GET_OperatorCircles] @Prefix,@ServiceTypeID ";
    SqlCommand cmd1 = new SqlCommand(SQL, con);

    cmd1.Parameters.AddWithValue("@Prefix", Phoneno);
    cmd1.Parameters.AddWithValue("@ServiceTypeID", servicetypeID);
    con.Open();
    cmd1.ExecuteNonQuery();

    SqlDataAdapter da = new SqlDataAdapter(cmd1);
    DataSet ds = new DataSet();
    // DataTable dt = new DataTable();
    da.Fill(ds);


    string json = JsonConvert.SerializeObject(ds, Formatting.Indented);

    return json;
}


[ActionName("getjsondata")]
[HttpGet]
public string getjsondata(string Phoneno, int servicetypeID)
{




    return json;
}

Actually what happend is in the above code I have two different methods but parametes are same.whenever I am calling getdata method,I am getting below response.

>An error has occurred.Multiple actions were found that match the request: 
getdata on type WebApi.Controllers.ValuesController
getjsondata on type WebApi.Controllers.ValuesControllerSystem.InvalidOperationException   at 

then how to call userdefine method in webapi.

Upvotes: 0

Views: 94

Answers (2)

abraganza
abraganza

Reputation: 135

If you are using Web Api 2, you could just define your routes using Attribute Routing. This will allow you to explicitly define routes for your Api and so the signature will not be an issue, i.e you could have something like this.

/api/myControllerPrefix/data
/api/myControllerPrefix/jsonData

Upvotes: 0

Christoph Fink
Christoph Fink

Reputation: 23103

How are you calling the method?
It looks like you are missing the id parameter in your request.
You can either add that to your request or make it "optional":

public string getjsondata(string Phoneno, int servicetypeID, int? id)
{
   if (!id.HasValue) { /* do something */ }
   // ....
}

BUT it seems you are not using it anyway, so maybe just remove it?

public string getjsondata(string Phoneno, int servicetypeID)

Upvotes: 1

Related Questions