ASP.NET Core - Calling Controller HTTP Endpoints a

2019-07-31 09:03发布

I have auto-generated a controller which handles creation / insertion / deletion of GearComponent (my custom class). This POST method for example handles the insertion of a GearComponent, later adding the correct primary key id from the database:

// POST: api/GearComponents
[HttpPost]
public async Task<IActionResult> PostGearComponent([FromBody] GearComponent gearComponent)
{
    if (!ModelState.IsValid)
    {
        return new BadRequestObjectResult(
            ModelState.Values
                .SelectMany(e => e.Errors)
                .Select(e => e.ErrorMessage));
    }

    _context.GearComponents.Add(gearComponent);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetGearComponent", new { id = gearComponent.Id }, gearComponent);
}

I want to continously write to the database while the ASP.NET Core 2.1 application is running (it is a "WebCrawler"-Thing). This thread lead me to this thread of how to implement a BackgroundService and register it on startup.

This is my service (it is just inserting dummy data):

public class WebCrawlerService : BackgroundService
{

    private readonly HttpClient client = new HttpClient();

    private readonly string requestUrl = "https://localhost:44377/api/controller/";

    public WebCrawlerService() { }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var httpContent = new StringContent(JsonConvert.SerializeObject(new GearComponent("Name", "Description", "08.12.2018")));
            var result = client.PostAsync(requestUrl, httpContent);
            await Task.Delay(2000);
        }
    }
}

While inserting the exact same GearComponent (the JSON-String is the same) with Postman works fine:

enter image description here

I always get

400 Bad Request

from this result (see WebCrawlerService):

var result = client.PostAsync(requestUrl, httpContent);

Why? Thanks to @Haldo it is working now:

var httpContent = new StringContent(JsonConvert.SerializeObject(new GearComponent("Name", "Description", "08.12.2018")), Encoding.UTF8, "application/json");

0条回答
登录 后发表回答