我是Asp.Net Core的新手,我正試圖建立一個API。我有以下的模型:
public class Location
{
public string Country { get; set; }
public string City { get; set; }
public string Street { get; set; }
我已經填充了我的資料庫,一個國家有多個城市,城市有多個街道。 我已經創建了一個End-point來回傳資料庫中的所有國家:
[HttpGet("cations")]
public async Task< ActionResult<IEnumerable<string>> GetCountries()
{
return await _context.Location. Select(x=>x.Country).Distinct().ToListAsync() 。
這將回傳一個字串陣列,我希望它能回傳以下JSON格式的回應:
這將回傳一個字串陣列。
[
{"country": "country1"}。
{"country": "country2"}。
..........
{"country": "countryN"}.
]
我的第二個端點是檢索一個特定國家的所有城市:
我的第二個端點是檢索一個特定國家的所有城市。
[HttpGet("cities/{country}")/span>]
public async Task<ActionResult<IEnumerable<string>> GetCites(string country)
{
--------- 缺少的代碼 ------
}
我已經嘗試了不同的選項,但我只設法獲得了兩個端點的字串陣列。我試著用IEnumerable替換IEnumerable,但沒有結果。
uj5u.com熱心網友回復:
對于第一個api,創建一個模型:
public class CountryResponse
{
public string Country { get; set; }
然后在API的回傳型別中使用這個模型類,并將結果回傳為:
[HttpGet("cations")]
public async Task< ActionResult< IEnumerable<CountryResponse>> GetCountries()
{
return await _context.Location. Select(x => new CountryResponse{ Country = x. Country }).Distinct().ToListAsync()。
類似地,對于第二個API,創建一個回應模型:
。public class CityResponse
{
public string City { get; set; }
而API將看起來像
[HttpGet("cities/{country}"/span>)]
public async Task< ActionResult< IEnumerable<CityResponse>>GetCites(string country)
{
return await _context.Location. Where(x => x.Country == country) 。 Select(x => new CityResponse { City = x. City }).ToListAsync()。
}
uj5u.com熱心網友回復:
該行
_context.Location。 Select(x=>x.Country).Distinct().ToListAsync()
回傳一個字串的串列,所以這就是ActionResult將回傳的內容。把它變成你想要的格式的最簡單方法是回傳一個KeyValuePair。如果你把回傳值改成這樣,它應該可以作業。
return await _context.Location.Select.Distinct()。 Select(country => new KeyValuePair< string, string>("country", country) )。 ToList()
與城市的想法相同,只需將它們放入一個KeyValuePair,你應該得到你需要的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/310052.html
標籤:
