개체를 ASP.NET Core의 파이프 라인에서 JSON 문자열로 직렬화하려면 개체 를 할당하는 데 쉽게 사용할 수있는 속성이 HttpContext.Response.Body.WriteAsync
없기 때문에 누락 된 항목이없는 Result
한을 사용해야 JsonResult
합니다.
더 나은 대안이 없다면 위의 방법을 사용하여 직렬화가 정확히 어떻게 이루어 집니까?
참고 : JSON serializer의 옵션은 ASP.NET Core 3.1에서 사용되는 (기본값) 옵션과 동일해야합니다.
원한다면 (우리의 경우는 아님) IServiceCollection.AddJsonOptions
미들웨어 를 통해 수정할 수 있습니다 .
예:
app.Use( next =>
{
return async context =>
{
if (<someFunkyConditionalExample>)
{
// serialize a JSON object as the response's content, returned to the end-user.
// this should use ASP.NET Core 3.1's defaults for JSON Serialization.
}
else
{
await next(context);
}
};
});
우선 다음과 같은 확장 메서드 를 사용 하여 응답에 직접 문자열을 쓸 수 있습니다 .
await context.Response.WriteAsync("some text");
다음 확장에 대한 액세스 권한을 부여하려면 올바른 네임 스페이스를 가져 왔는지 확인하십시오.
using Microsoft.AspNetCore.Http;
둘째, 프레임 워크에서 사용중인 JSON 시리얼 라이저 설정을 얻으려면 DI 컨테이너에서 추출 할 수 있습니다.
var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();
따라서 전체 파이프 라인 코드가 다음과 같이 보일 것입니다.
app.Use(next =>
{
return async context =>
{
if (<someFunkyConditionalExample>)
{
// Get the options
var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();
// Serialise using the settings provided
var json = JsonSerializer.Serialize(
new {Foo = "bar"}, // Switch this with your object
jsonOptions?.Value.JsonSerializerOptions);
// Write to the response
await context.Response.WriteAsync(json);
}
else
{
await next(context);
}
};
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다