2017-10-26 2 views
1

MVC 컨트롤러를 사용하여 REST API 요청을 처리하는 ASP.NET Core 2.0을 사용하고 있습니다. Chrome을 사용하여 응답을 보았을 때 모든 것이 정상적으로 보였지만 Angular 2 HttpClient를 사용하여이를 소비하려고 시도하면 오류가 발생합니다 (그리고 절망적으로 이유를 알 수 없습니다). 나는 왜 그런지 알 것 같아. Fiddler를 사용하여 ASP.NET 응용 프로그램에서 오는 원시 HTTP 응답을 검사 할 때 응답 본문 앞에 "f6"과 "0"이옵니다. 왜 그렇게했을까요?ASP.NET Core 2.0 렌더링 이상한 JSON 몸체 - 각도 HttpClient 끊기

HTTP/1.1 200 OK 
Transfer-Encoding: chunked 
Content-Type: application/json; charset=utf-8 
Server: Kestrel 
Access-Control-Allow-Origin: * 
X-Powered-By: ASP.NET 
Date: Thu, 26 Oct 2017 17:14:27 GMT 

f6 
[{"Id":1,"name":"Hello World"}] 
0 

FOLLOW-UP : : 지금은이 작업을 수행하는 이유를 알고 여기에 내가 갖는 응답의 예입니다. 그것은 "Transfer-Encoding : chunked"를 사용하고, 선도 f6는 청크의 크기를 나타내고, 마지막 0은 최종 0 길이 청크를 나타냅니다.

여기 API를 다시 호출하는 각도 서비스입니다. 미안하지만 좀 복잡한 데요 제 코드를 사용하여 코드를 간결하게 만드십시오. 그것은 return 문에 결코 부딪치지 않습니다. .get() 호출 어딘가에 폭탄이 있어야합니다.

import { Injectable } from "@angular/core"; 
import { HttpClient } from "@angular/common/http"; 

import 'rxjs/add/operator/toPromise'; 

@Injectable() 
export class BaseService { 
    constructor(private _http: HttpClient) { 
    } 

    protected getAPIObject<T>(targetUrl: string): Promise<Array<T>> { 
     return this._http.get(targetUrl).toPromise().then(data => { 
      return data as Array<T>; 
     }); 
    } 
} 

그리고 또한 매우 재미 있지, 각도 위는 ("GET"을 시도하는 웹 서비스에 대한 내 Startup.cs 클래스 스포일러 : 나는 잘못이이를 왜 아래 답변을 참조하십시오. 관심 분야!)

public class Startup 
{ 
    public Startup(IConfiguration configuration) 
    { 
     Configuration = configuration; 
    } 

    public IConfiguration Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container. 
    public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddMvc(); 

     services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); 
     services.Configure<SqlStatementSettings>(Configuration.GetSection("SqlStatements")); 
     services.AddSingleton<IObjectRepository, ObjectRepository>(); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 

     app.UseMvc(); 
    } 
} 
+1

Postman 또는 Fiddler를 사용하여 게시하고 가져 오는 경우 Angular를 사용하기 전에 API가 예상 한 결과를 반환합니까? – Win

+0

예, Chrome에 API URL을 입력하고 피들러를 살펴본 후에도 응답에서이 동일한 형식을 볼 수 있습니다. 크롬은 어떻게 처리해야하는지 알고있는 것 같습니다. –

+0

Btw, https://jsonplaceholder.typicode.com/posts에 직접 호출하여 HttpClient가 작동 함을 입증했습니다. 그것은 아름답게 처리합니다. –

답변

0

나는 그것을 이해했다. .. 그리고 나는 길로부터 떨어진 길이었다. 내 JSON을 둘러싼 "f6"과 "0"은 "Transfer-Encoding : chunked"(원래 질문에 추가됨)를 사용했기 때문에 발생했습니다. 내 문제의 원인은 CORS를 제대로 설정하지 않았다는 것입니다. 아래는이 실수에 대한 나의 교정입니다. 이전에 CORS를 설정하려고 시도했지만 실제로 작동하지 않았습니다 ... "UseMvc"를 추가 한 후 "UseCors"를 추가했기 때문에 미들웨어를 함께 연결할 때 문제가 발생합니다. Btw, 프로덕션을 위해 AllowAnyOrigin을 사용하지 않는 것이 좋습니다. 이것이 내 개발 수정입니다.

public class Startup 
{ 
    public Startup(IConfiguration configuration) 
    { 
     Configuration = configuration; 
    } 

    public IConfiguration Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container. 
    public void ConfigureServices(IServiceCollection services) 
    { 

     services.AddCors(options => 
     { 
      options.AddPolicy("AllowAnyOrigin", policy => policy.AllowAnyOrigin()); 
     }); 

     services.AddMvc(); 

     services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); 
     services.Configure<SqlStatementSettings>(Configuration.GetSection("SqlStatements")); 
     services.AddSingleton<IObjectRepository, ObjectRepository>(); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 

     app.UseCors("AllowAnyOrigin"); 

     app.UseMvc(); 
    } 
}