Возвращает json из. net core api при использовании NotFound () - PullRequest
0 голосов
/ 22 апреля 2020

Я пытаюсь сделать так, чтобы мое ядро ​​web api возвращало приложение / json, но, как ни странно, оно всегда возвращает эту html страницу, нарушающую соглашение об ошибках, установленное командой.

Вот код i ' я пытаюсь выполнить, но пока безуспешно:

Startup.cs

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddControllers().AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" });
        });

        services.AddMvcCore().AddRazorViewEngine().AddRazorRuntimeCompilation().ConfigureApiBehaviorOptions(options =>
        {
            options.InvalidModelStateResponseFactory = actionContext =>
            {
                var errorList = (from item in actionContext.ModelState
                                 where item.Value.Errors.Any()
                                 select item.Value.Errors[0].ErrorMessage).ToList();
                return new BadRequestObjectResult(new
                {
                    ErrorType = "bad_request",
                    HasError = true,
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Message = "Formato do request inválido",
                    Result = new
                    {
                        errors = errorList
                    }
                });
            };
        });
    }

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

        app.UseMiddleware(typeof(ErrorHandlingMiddleware));

        app.UseCors(
            options => options.AllowAnyOrigin().SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader()
        );

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

AuthController.cs

[HttpPost("refreshtoken")]
public IActionResult PostRefreshToken(Guid token)
{
    if (!_authTokenService.IsValid(token))
    {
        return NotFound(new JsonResponse
        {
            HasError = true,
            ErrorType = "not_found",
            StatusCode = (int)HttpStatusCode.NotFound,
            Title = "Token não encontrado",
            Message = "refresh is not valid because it was not found or does not comply",
        });
    }

    var savedToken = _authTokenService.Get(token);
    ...

    return Ok(new JsonResponse
    {
        StatusCode = (int)HttpStatusCode.OK,
        Title = "Token atualizado",
        Message = "jwt access token refreshed with success, please update your keys for subsequent requests",
        Result = new
        {
            Expiration = accessToken.Expiration.ToString("dd/MM/yyyy HH:mm:ss"),
            AccessToken = accessToken.Token,
            RefreshToken = refreshToken.Token,
         }
    });
}

когда был выполнен этот код, я был ожидание результата json при достижении блока NotFound (), но вместо этого он возвращает этот текст / html page

enter image description here

ErrorHandlingMiddleware.cs

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;
    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context /* other dependencies */)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        var code = HttpStatusCode.InternalServerError;

        var result = JsonConvert.SerializeObject(new
        {
            HasError = true,
            StatusCode = (int)code,
            Message = ex.Message
        }, new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy()
            }
        });

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}

1 Ответ

0 голосов
/ 28 апреля 2020

В моем случае это было расширение Visual Studio Конвейер от Keyoti , являющийся виновником вышеупомянутых ошибок.

Когда я отключил расширение, оказалось, что код в порядке и возвращая правильный код, тело объекта json, отправленное сервером.

...