Home > Enterprise >  Asynchronous API method [closed]
Asynchronous API method [closed]

Time:09-16

I have a web API method that checks a file which user uploads. It checks for viruses, file type and so on. This is being checked for 1-2 minutes (because this checking is being done in servers I don't have access to, long story) and user has to wait 1-2 minutes while his file is being checked, and then API receives and returns message "Your upload is (not) successful" to my Angular project.

Well, what I want is to make a call to API but while the file is being checked I want to allow user to freely navigate through the app. And when the checking is finished, I want to give him a note (on whatever page he is on in that moment) that his upload was successful or unsuccessful.

I don't know if this is possible to make, I assume I have to turn my method to asynchronus in API, but I don't know where to start (new to this). Any tips will be great.

This is my current method in API:

public HttpResponseMessage Create()
{
    try
    {
        HttpRequest request = HttpContext.Current.Request;

        HttpPostedFile file = request.Files[0];
        string fileExtension = Path.GetExtension(file.FileName);
        string fileName = Path.GetFileNameWithoutExtension(file.FileName);
        string fileFolder = GetFolder();
        sqlDataAccess.ExecuteQuery("spCreateDokument", ar); //I deleted ar declarations and filling, to reduce code

        int id = sqlDataAccess.GetParamValue<int>(ar, "@Id");

        // file is saved to disk
        string filePath = Path.Combine(GetFolder(), id.ToString()   Path.GetExtension(file.FileName));
        file.SaveAs(filePath);

        return Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (Exception ex)
    {
        throw ProcessException(ex, System.Reflection.MethodBase.GetCurrentMethod());
    }
}  

CodePudding user response:

There are two possible options to implement that. It's either poll an endpoint or implement WebSockets (ASP.NET SignlarR is a wrapper over raw WebSockets). So your backend needs to know when validation of your file is done. But if you don't have access to the code which runs the validation itself, you need to know which mechanism it provides in order to get information when it's done. If could be you also need to poll or maybe there is a webhook etc. When it comes to polling versus WebSockets. The main difference during polling, client code will shoot requests on schedule to the backend with the question: "Is it already done?", while with WebSockets: a client will subscribe and listen to the backend: "As soon as it is done, please notify me". So overall, WebSockets is a better option, but the implementation will be more complex. Up for you to decide which way to take

  • Related