简体   繁体   中英

C# ASP.NET Core Web API: How to maintain context in the controller between calling different methods

C# ASP.NET Core Web API: general newbie question. Trying to implement basic Asynchronous Request-Reply Pattern. Basic idea is that:

  1. Client calls POST {url}/DataProcessor/DataX with some payload
  2. Client checks on the status of the transaction using GET {url}/DataProcessor/DataXStatus , until HTTP Status Code of 200 is returned
  3. Client gets xActionId from the response above and then calls GET {url}/DataProcessor/GetResults/{xActionId} to retrieve results of data processing.

This is what my controller looks like: When I call DataXStatus method (after properly calling the DataX method), the _processData isn't in the right state, like it has gone out of scope after DataX method is done. What am I doing wrong? Is DataProcessorController object gone after any one method is complete? What is the right way to do this?

Thanks in advance

[Route("[controller]")]
[ApiController]
public class DataProcessorController : ControllerBase
{
    private ProcessData _processData = new ProcessData() ;

    [HttpPost]
    [Route("DataX")]
    public IActionResult DataX([FromBody] xData value)
    {
        _processData.CalculateResult(value);
        return Accepted();
    }

    [HttpGet]
    [Route("DataXStatus")]
    public IActionResult DataXStatus()
    {
        if(_processData.IsRunning())
        {
            return Accepted();
        }
        return Ok(new xDataStatus(){id = _processData.GetxActionId()});
    }

    [HttpGet]
    [Route("GetResults/{xActionId}")]
    public IActionResult GetResults(string xActionId)
    {
        return Ok(new xDataResults(){resX = _processData.GetResults()});
    }
}

Answering this on my mobile so please forgive any typos.

Basically, yes the class is re-instaintaited on every request. The api does not keep context of previous requests unless the object you are keeping track of is static, which being me to my first solution for this:

Quick and dirty option:

I would recommend you use dependency injection for this instead. That gives you the option to run your 'proccessData' class as a singleton. Which basically means it's static.

Better option:

The other more correct way is to use a known library for this. There are are tons of libraries that are built for handling async requests in web apis. I think you should use hangfire for this, it takes a few minutes to set up and also has tons of configurion options.

https://docs.hangfire.io/en/latest/getting-started/as.net-core-applications.html

Let me know if you need any further help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM