How to return a return value from Hangfire
Asked Answered
K

2

11

I noticed this field in the Hangfire Dashboard for a succeeded job:

enter image description here

I would love to shove some data in there, to give me more information about what the job did.

How would I do that?

I have searched google, checked the Hangfire documentation etc, but with no luck - probably because "result" is a very tricky keyword to search for in this context.

Kunzite answered 1/9, 2019 at 19:26 Comment(0)
B
12

The "Result" field displays the output/result your method returns.

You can return a string or object and Hangfire will convert it to JSON.

Your "Result" field contains a serialization error, Hangfire is failing to serialize the returned object but without any code I cannot help you further.

Please see example screenshots below.

Code: Result: Code: Result:

Bergamot answered 16/9, 2019 at 7:9 Comment(1)
...I have had so many problems trying to write to the Hangfire log int he past, I did not even consider that the solution could be so simple and straightforward. Thanks! :)Kunzite
D
6

To programmatically get returned value, use IMonitoringApi.
E.g. Helper method to get List<TReturn>:

List<TReturn> GetReturnedItems<TReturn>(string jobId)
{
    IMonitoringApi jobMonitoringApi = JobStorage.Current.GetMonitoringApi();
    JobDetailsDto job = jobMonitoringApi.JobDetails(jobId);
    string resultSerialized = job.History[0].Data["Result"];
    List<TReturn> returnedItems = JsonConvert.DeserializeObject<List<TReturn>>(resultSerialized);
    return returnedItems;
}
Doordie answered 17/8, 2020 at 22:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.