【发布时间】:2019-06-25 20:48:43
【问题描述】:
我开始了 Angular 2+ (v8) 之旅,遇到了一些关于使用异步 c# WebApi 函数的最佳实践的问题。最后的问题:
在我的示例 WebApi 中(请注意,这将在未来以异步方式调用存储库,但目前不为简洁起见)我具有以下功能:
// GET api/values
[HttpGet]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(Task<IEnumerable<SearchResult>>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> Get([FromQuery]string searchText, [FromQuery]int pageSize = 10, [FromQuery]int pageIndex = 0)
{
if (string.IsNullOrEmpty(searchText))
{
return BadRequest();
}
//Call a repository here and return a result
var searchResults = new List<SearchResult>()
{
new SearchResult()
{
SearchResultType = SearchResultType.Law, Id = Guid.NewGuid(),
Title = "A boring title",
Description = "A boring decription"
},
new SearchResult()
{
SearchResultType = SearchResultType.Law, Id = Guid.NewGuid(),
Title = "An interesting title",
Description = "An exciting description"
},
};
return Ok(await Task.FromResult(searchResults.Where(x => x.Title.Contains(searchText))));
}
这会返回 Task<IActionResult> 并且我已经使用 Swagger 装饰器说路线返回 [ProducesResponseType(typeof(Task<IEnumerable<SearchResult>>) 。然而,在招摇示例响应中,则需要一个任务模型:
{
"result": [
{
"searchResultType": "Law",
"id": "string",
"title": "string",
"description": "string"
}
],
"id": 0,
"exception": {},
"status": "Created",
"isCanceled": true,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": "None",
"asyncState": {},
"isFaulted": true
}
实际响应是:
[
{
"searchResultType": 1,
"id": "0ba4e4ef-37fd-4a76-98ed-4fad64d26b1b",
"title": "A boring title",
"description": "A boring description."
},
{
"searchResultType": 1,
"id": "e8c7e39d-cca6-43b2-90be-87537a4a0b8e",
"title": "An exciting title",
"description": "An exciting description."
}
]
在 Angular 8 中,我使用的服务是:
@Injectable()
export class SearchService {
constructor(private http: HttpClient) {}
search(
filter: { searchTerm: string } = { searchTerm: "" },
page = 1
): Observable<ISearchResult[]> {
return this.http.get<ISearchResult[]>("api/v1/Search?searchText=" + filter.searchTerm);
}
}
所以问题:
[ProducesResponseType(typeof(Task<IEnumerable<SearchResult>>)真的应该是[ProducesResponseType(typeof(IEnumerable<SearchResult>)吗?Task<>会返回给客户吗?
我问这个是因为我最初忘记了await api 中的返回值,并且任务模型实际上返回给了 Angular 客户端,然后在 Angular 服务中我不得不使用以下内容来获得混乱的结果:
return this.http.get<ISearchResult[]>("api/v1/Search?searchText=" + filter.searchTerm)
.pipe(
map((res:ISearchResult[]) => res.result)
);
- 我这样做是否正确?有没有更好的办法 ?
【问题讨论】:
标签: angular async-await task swagger asp.net-core-webapi