[英]How can web API take list and return different type for ASP.NET web API
我在一個項目中,我想在一個Web API方法中添加list<restaurant >
,並返回restaurant和rest_location之間的不同類型的混合。 restaurant和rest_location之間的關系是一對多的。
當我運行它時,出現錯誤:
{“消息”:“請求的資源不支持http方法'GET'。”}
服務器Web API:
[HttpPost]
[Route("api/Restaurants/res_by_locat/{x}/{res_loc}")]
[ResponseType(typeof(Restaurant))]
[ResponseType(typeof(Rest_Location))]
public HttpResponseMessage GetResturantsBylocation([FromUri]int x,[FromBody] List<Rest_Location> res_loc)
{
List<Table> table = new List<Table>();
var lstitem = from t1 in res_loc
from t2 in db.Restaurants.Where(y => y.R_ID == t1.R_ID )
.DefaultIfEmpty()
select new { t1.L_Adress, t2.R_Name };
//foreach (var item in lstitem)
//{
// table.Add(item);
//}
if (lstitem == null || !lstitem.Any())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
else return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, new { lstitem });
}
客戶:
protected void btn_ddl_Click(object sender, EventArgs e)
{
if (locationddl.SelectedValue == "0")
{
lbl_result.Text = "Chose a Location First ! ";
}
else
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:10566/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var fromddl = locationddl.SelectedItem.Text;
//lbl_result.Text = fromddl;
var response = client.GetAsync("api/Locations/getid_by_name/" + fromddl).Result;
// if (Page.IsValid)
{
if (response.IsSuccessStatusCode)
{
Location ll = response.Content.ReadAsAsync<Location>().Result;
int x = ll.L_ID;
lbl_msg.Text = x.ToString();
var response2_get_ids_Rests = client.GetAsync("api/Rest_Location/res_by_locat/" + x).Result;
if (response2_get_ids_Rests.IsSuccessStatusCode)
{
List<Rest_Location> rests_locations = response2_get_ids_Rests.Content.ReadAsAsync<List<Rest_Location>>().Result;
//var items= rests_locations.FirstOrDefault(rl => rl.L_ID == x);
// GridView2.DataSource = rests_locations;
// GridView2.DataBind();
HttpResponseMessage response3_get_resturants_by = client.PostAsJsonAsync("api/Restaurants/res_by_locat/" + x , rests_locations).Result;
if (response3_get_resturants_by.IsSuccessStatusCode)
{
var news= response3_get_resturants_by.Content.ReadAsAsync<List<Restaurant>>().Result;
GridView1.DataSource = news;
GridView1.DataBind();
lbl_msg.Text = "Search succesed";
}
else
{
lbl_test.Text = " not found ";
}
}
else
{
lbl_test.Text = " not found ";
}
}
}
}
catch (Exception ex)
{
lbl_msg.Text = "Couldn't Found Resaurants ! " + ex.ToString();
}
}
}
您的端點具有此屬性[HttpPost]
,這意味着只能使用POST
訪問它
您的客戶端正在嘗試使用GET
訪問端點。
您應該使用client.PostAsync
方法而不是GetAsync
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.