2015-10-20 37 views
0

我正在開發wepapi service.Below是我的代碼。如何在webapi中調用用戶定義方法

[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; 
} 

其實是發生了什麼在上面的代碼,我有兩個不同的方法,但指標的影響是same.whenever我調用GetData方法,我得到如下回應。

>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 

那麼如何在webapi中調用userdefine方法。

+0

@Webruster請參閱我的代碼。 –

回答

1

你打電話的方法怎麼樣?
看起來您在請求中缺少id參數。
您可以添加到您的請求或使其「可選」:

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

但似乎你不使用它,無論如何,所以也許只是將其刪除?

public string getjsondata(string Phoneno, int servicetypeID) 
+0

http:// localhost:23456/api/values/getdata?Phoneno = 23456789&servicetypeID = 1.這種方式我打電話給 –

+0

@AnilKumar:懷疑沒有'id'參數 - 'http:// localhost:23456/api/values/getjsondata?Phoneno = 23456789&servicetypeID = 1&id = 1'或將其刪除,因爲它沒有被用到...... – ChrFin

+0

ok id沒有用過。我的問題是Iam調用getdata方法。該方法Iam只放置兩個參數 –

0

如果您正在使用網絡API 2,你可以只使用Attribute Routing定義你的路由。這將允許你明確地定義你的Api的路由,所以簽名不會成爲問題,即你可以有這樣的事情。

/api/myControllerPrefix/data 
/api/myControllerPrefix/jsonData 
相關問題