【问题标题】:nswag generated client with wrong response typenswag 生成的客户端响应类型错误
【发布时间】:2020-05-31 06:19:45
【问题描述】:

这是在 nswag swagger 客户端生成的帮助下从 C# 控制器自动生成的 Angular 服务文件。下面的代码具有所有服务。在组件中,我试图调用 getCompanyInfoOption() api。但我没有收到从控制器发送的响应数据。

/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v13.6.0.0 (NJsonSchema v10.1.18.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable({
providedIn:'root'
})
export class CompanyInfoService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44311";
    }

    getCompanyInfoOption(): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetCompanyInfoOption(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetCompanyInfoOption(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetCompanyInfoOption(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

如何在我的组件中调用此服务?我正在尝试使用组件的 ngOnInit 中的 subscribe 方法调用

  ngOnInit(): void {
      this.service.getCompanyInfoOption().subscribe(
        value => {
          console.log(value);
        },
        error => console.error(JSON.stringify(error)),
        () => console.log('done')
      );
  }

我在调用 getCompanyInfoOption api 后得到这个输出

Console Log

我的 c# 控制器

ASP .net core C# controller

compantInfoOption send in ok 的响应类型如下所示

conpanyInfoOption type

【问题讨论】:

    标签: c# angular nswag


    【解决方案1】:

    我猜生成的代码有问题,因为你的控制器返回类型不正确,尝试使用ActionResult,然后生成的api将返回正确的结果而不是期待文件响应。

    你的情况

    public async Task<ActionResult<CompanyInfoOptionAc>> GetCompanyInfo(){
    //etc
    }
    

    【讨论】:

    • 谢谢你,你在控制器中是对的,我的返回类型应该是 Task>
    • 我建议更新问题标题,以便其他人在寻找它时可以找到它,例如,nswag 生成的客户端期望文件响应或 nswag 生成的客户端具有错误的响应类型。我很乐意提供帮助
    【解决方案2】:

    看来你是。因为您的响应类型是 FileResponse 并且在 console.log 中您可能会看到这个对象。在数据中存储的其他内容 blob 以及如果您需要文本解释,如果它只是使用像 blobToText 这样位于生成文件末尾的函数。

    如果我错了,请在问题中添加期望结果。

    【讨论】:

    • 我将如何获得预期结果?
    • 你需要从blob中取出或者使用json
    • 在控制器中我的返回类型错误,这就是发生错误的原因
    猜你喜欢
    • 2021-01-15
    • 1970-01-01
    • 2021-12-21
    • 2021-11-18
    • 1970-01-01
    • 2020-04-11
    • 2018-11-09
    • 2018-02-25
    • 2021-07-27
    相关资源
    最近更新 更多