[英]Call get method in web api with multiple parameters from c#
我正在嘗試在 web api 中調用 get 方法,該方法將從客戶端獲取 2 個參數。 在這里,用戶將輸入用戶名和密碼,並將其發送到服務器進行身份驗證。
這是我的控制器供應商(我在 mvc 中創建的)及其 web api 方法
[Route("api/Vendor/{uname}/{pass}")]
public int Get(string uname, string pass)
{
Boolean exists = false;
int id = 0;
SqlConnection con = new SqlConnection(" Data Source = DELL; Initial Catalog = EVENT; Integrated Security = True");
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Count([UserName]) As Usercount FROM [dbo].[AllUser] WHERE [UserName] = '" + uname + "' AND [Password] = '" + pass + "' ", con))
{
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
SqlCommand cmd = new SqlCommand("SELECT [Id] FROM [dbo].[AllUser] WHERE [UserName] = '" + uname + "' AND [Password] = '" + pass + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
id = Convert.ToInt16(ds.Tables[0].Rows[0][0]);
}
return id;
}
現在我被困在如何向這個 api 發送 2 個參數。 我是否必須將它們轉換為 JSON,或者我可以直接發送它們。 我不知道如何調用這個獲取方法。
我在客戶端使用 c# 和 android。 請給我有關如何從雙方調用此方法的建議。
謝謝。
實際上我用以下代碼更新了我的 c# 客戶端
static async Task<int> ValidateVendorAsync(string uname, string pass)
{
int id = 0;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56908/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
HttpResponseMessage response = await client.GetAsync("api/Vendor/" + uname + "/" + pass);
if (response.IsSuccessStatusCode)
{
System.Diagnostics.Debug.WriteLine("Con");
}
else
{
System.Diagnostics.Debug.WriteLine("Connection Error");
}
return id;
}
}
但是代碼不起作用。 await client.GetAsync之后的代碼沒有執行。 如何解決這個問題?
您已正確設置所有內容,您只需要對該 url 發出 HTTP GET 請求: http://baseurl/api/Vendor/myusername/mypassword
路由中傳遞的參數不需要序列化。 如果它們沒有在路由中聲明,那么您必須傳遞一個序列化版本。 在這種情況下,它們將作為查詢字符串的一部分附加。
因此,使用您的 HttpClient 示例:
var client = new HttpClient() //if used frequently, don't dispose this guy, make him a singleton if you can (see link below)
String uname = UserName.Text;
String pass = Password.Text;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
var result = await client.GetAsync("http://localhost:56908/api/vendor/" + uname + "/" + pass);
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
您必須將參數傳遞到查詢字符串中,如下所示,
http://localhost:49996/api/Vendor?uname=CharanGhate&pass=xyz
http://localhost:49996/是應用程序的基本 url。 您必須在此處使用 http get 方法。 您也可以直接從瀏覽器調用 get 類型方法,也可以從 postman、fiddler 等調用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.