Получение 404 ответа от Web API на действие POST - PullRequest
2 голосов
/ 10 марта 2020

Консольное приложение выполняет вызов веб-API, но получает ответ 404.

Массив responseBytes в клиенте ниже при преобразовании в строку с использованием System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); возвращает следующее HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>

Вызов клиента

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(action);//action=http://<my-app>/headcount/comparison/zip
    _logger.InfoFormat("downloading files from {0}", action);
    var response = await client.PostAsync(action, new StringContent(jsonInString, Encoding.UTF8, "application/json"));
    responseBytes = await response.Content.ReadAsByteArrayAsync();
}

Контроллер / действие:

[ApiController]
[Route("[controller]")]
public class HeadcountController : ControllerBase
{

    [HttpPost]
    [Route("comparison/zip")]
    [Consumes("application/json")]
    public IActionResult GetReports(ReportRequest request)
    {
        //action details...never reached
    }
}

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.AddControllers().AddNewtonsoftJson();
    }

    // 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.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

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

Что я делаю не так?

1 Ответ

0 голосов
/ 10 марта 2020

Вам может потребоваться установить тип контента client на application/x-www-form-urlencoded.

    client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...