DEV Community

Discussion on: How to Add Generated HttpClient to ASP.NET Core Dependency Injection (Right Way)

angellaguna profile image

Hi. I have a question,
if my response is a Ok and BadRequest,
how can i get the data this request?

dr_dimaka profile image
Dmitry Pavlov Author

If you are generating with NSwag for your API controller - add attributes and return the object from the action - something like this:

[SwaggerResponse(HttpStatusCode.OK, typeof(MyOkResponse))]
[SwaggerResponse(HttpStatusCode.BadRequest, typeof(string))]
public async Task<ActionResult<MyOkResponse>>  GetMyResponseAsync(CancellationToken token)
  var myResponse = await GetMyDataAsync();
  try { 
    return OK(myResponse);
  } catch (Exception ex) {
    return BadRequest(ex.Message);
Enter fullscreen mode Exit fullscreen mode

In this case NSwag will know how to interpret your responses - see in generated code how to retrieve error details from ApiException generated client will throw for any non OK response you defined.