Код: Выделить всё
[Function("businessOrderRequest")]
[OpenApiOperation(operationId: "Run")]
[OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
[OpenApiParameter("businessOrder", Type = typeof(string), In = ParameterLocation.Path, Required = true, Summary = "businessOrder of the customer", Description = "Path containing the businessOrderRequest as a parameter")]
[OpenApiRequestBody("application/json", typeof(BusinessOrderRequest), Description = "Request Body has input fields which are used to insert Cart Details")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(string),
Description = "The OK response message containing a JSON result.")]
public async Task RunAsync([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
{
var response = req.CreateResponse();
var baseResponse = new BaseResponse();
try
{
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var data = JsonConvert.DeserializeObject(requestBody);
var responseData = await CreateBusinessOrderService.CreateBusinessOrderAsync(data);
baseResponse.payload = responseData;
response.StatusCode = HttpStatusCode.OK;
}
catch (Exception ex)
{
baseResponse.error_messages.Add($"An unexpected error occurred. {ex.Message}");
_logger.LogError(ex, "An error occurred processing the request.");
}
// Write the response
await response.WriteAsJsonAsync(baseResponse);
return response;
}
На этой строке кода:
Код: Выделить всё
var responseData = await CreateBusinessOrderService.CreateBusinessOrderAsync(data);
< /code>
Я получаю ошибку < /p>
Ссылка на объект требуется для нестатического поля, метода или свойства < /p>
< /blockquote>
Это класс Сервиса (CreateBusinessOrderService.csКод: Выделить всё
public async Task CreateBusinessOrderAsync([FromBody] BusinessOrderRequest businessOrderRequest)
{
string quizJson = System.Text.Json.JsonSerializer.Serialize(businessOrderRequest);
var response = new EmailResponse();
response.Success = false;
string attachmentName = string.Empty;
try
{
#region Read EmailSettings based on provider
var emailSettings = _bizCartemailSettingOptions.Value.Options.Where(x => x.Provider.ToLower() == businessOrderRequest?.ProviderName.ToLower()).ToList().FirstOrDefault();
var EmailFrom = emailSettings?.FromEmail;
var EmailSubject = emailSettings?.Subject;
var EmailClient = emailSettings?.SMTPServer;
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", emailSettings?.TemplateName);
#endregion
string htmlContent = System.IO.File.ReadAllText(filePath);
var emailBody = GenerateEmailBody(businessOrderRequest, htmlContent);
#region Sending Email to customer
if (!string.IsNullOrEmpty(emailBody))
response = SendEmailToCustomer(businessOrderRequest, EmailFrom, EmailSubject, EmailClient, emailBody);
#endregion
}
catch (Exception ex)
{
this._logger.LogError($"Error occurred in BizCartController CreateBusinessOrderAsync method.");
//return this.StatusCode(StatusCodes.Status500InternalServerError,
// new SimpleErrors(new SimpleError($"Error occurred in BizCartController CreateBusinessOrderAsync method.")));
}
await response.;//.WriteAsJsonAsync(response);
return response;
}
Код: Выделить всё
public class EmailResponse
{
public bool Success { get; set; }
}
В классе службы я хочу получить ответ. Как написать правильный код для службы, где я хочу использовать метод в качестве асинхронного? Businessorder я получу от пользовательского интерфейса, который я хочу использовать в качестве корпуса формы.
Согласно требованию, я отправлю почту, как только получу ответ.
Подробнее здесь: https://stackoverflow.com/questions/796 ... ync-method
Мобильная версия