Я создал решение ASP.NET Core API, которое использует RestSharp для отправки данных стороннему API и возврата результатов обратно в мой API и базу данных. В моем API я хочу вернуть результаты вызова RestSharp как часть моего класса контроллера, чтобы мой сайт DNN мог использовать ответы RestSharp. Как вернуть ответы, полученные от стороннего API в моем классе контроллера?
Моя логика RestSharp выглядит следующим образом:
/// <summary>
/// Executes a particular http request to a resource.
/// </summary>
/// <typeparam name="T">The response type.</typeparam>
/// <param name="request">The REST request.</param>
/// <param name="baseUrl">The base URL.</param>
/// <returns>Returns a response of the type parameter.</returns>
private static T Execute<T>(IRestRequest request, string baseUrl) where T : class, new()
{
baseUrl = "https://xmltest.propay.com/api/propayapi/PropayMerchantService.svc/";
var client = new RestClient(baseUrl);
var response = client.Execute<T>(request);
if (response.ErrorException != null)
{
Console.WriteLine(
"Error: Exception: {0}, Headers: {1}, Content: {2}, Status Code: {3}",
response.ErrorException,
response.Headers,
response.Content,
response.StatusCode);
}
return response.Data;
}
public static ProPayResponse MerchantSignUpForProPay()
{
var baseUrl = "https://xmltest.propay.com/api/propayapi/PropayMerchantService.svc/";
var request = BuildMerchantTestData();
var restRequest = CreateRestRequest("/Signup", Method.PUT);
restRequest.AddJsonBody(request);
return Execute<ProPayResponse>(restRequest, baseUrl);
}
/// <summary>
/// Builds the merchant request data.
/// </summary>
/// <returns>The request data.</returns>
private static SignUpRequest BuildMerchantTestData()
{
var onboarding = new Onboarding();
var signUpRequest = new SignUpRequest();
var userid = "userId";
var email = userid + "@test.com";
using (SOBOContext context = new SOBOContext())
{
var signupRequest = new SignUpRequest
{
SignupAccountData = new SignupAccountData
{
ExternalId = "12345",
Tier = onboarding.AverageTicket.ToString(),
CurrencyCode = "USD",
PhonePIN = onboarding.PhonePin,
UserId = onboarding.UserName
},
Address =
new Address
{
Address1 = onboarding.Address1Line1,
Address2 = onboarding.Address1Line1,
ApartmentNumber = " ",
City = onboarding.Address1City,
State = onboarding.Address1State,
Country = onboarding.Address1Country,
Zip = onboarding.Address1ZipCode
},
BusinessAddress =
new Address
{
Address1 = onboarding.BusinessAddressLine1,
Address2 = onboarding.BusinessAddressLine2,
ApartmentNumber = " ",
City = onboarding.BusinessCity,
State = onboarding.BusinessState,
Country = onboarding.BusinessCountry,
Zip = onboarding.BusinessZipCode
},
MailAddress = new Address { Address1 = onboarding.OwnerAddress, City = onboarding.OwnerCity, State = onboarding.OwnerRegion, Country = onboarding.OwnerCountry, Zip = onboarding.OwnerZipCode },
BankAccount =
new BankAccount
{
AccountCountryCode = onboarding.BankAccount1CountryCode,
AccountType = onboarding.BankAccount1Type,
AccountOwnershipType = onboarding.BankAccount1OwnershipType,
BankAccountNumber = onboarding.BankAccount1Number,
BankName = onboarding.BankAccount1BankName,
RoutingNumber = onboarding.BankAccount1RoutingNumber
},
SecondaryBankAccount =
new BankAccount
{
AccountCountryCode = onboarding.BankAccount2CountryCode,
AccountType = onboarding.BankAccount2Type,
AccountOwnershipType = onboarding.BankAccount2OwnershipType,
BankAccountNumber = onboarding.BankAccount2Number,
BankName = onboarding.BankAccount2BankName,
RoutingNumber = onboarding.BankAccount2RoutingNumber
},
BusinessData =
new BusinessData
{
BusinessLegalName = onboarding.BusinessLegalName,
DoingBusinessAs = onboarding.DoingBusinessAs,
EIN = onboarding.Ein,
},
CreditCardData = new CreditCardData
{
CreditCardNumber = onboarding.CreditCardNumber, // test card number
ExpirationDate = onboarding.ExpirationDate
},
PersonalData =
new PersonalData
{
DateOfBirth = onboarding.DateOfBirth.ToString(),
SourceEmail = onboarding.Email,
SocialSecurityNumber = onboarding.Ssn,
FirstName = onboarding.FirstName,
LastName = onboarding.Lastname,
MiddleInitial = onboarding.MiddleInitial,
PhoneInformation =
new PhoneInformation { DayPhone = onboarding.DayPhone, EveningPhone = onboarding.EveningPhone }
}
};
context.SaveChangesAsync();
return signupRequest;
}
}
/// <summary>
/// Request factory to ensure API key is always first parameter added.
/// </summary>
/// <param name="resource">The resource name.</param>
/// <param name="method">The HTTP method.</param>
/// <returns>Returns a new <see cref="RestRequest"/>.</returns>
private static RestRequest CreateRestRequest(string resource, Method method)
{
var credentials = GetCredentials();
var restRequest = new RestRequest { Resource = resource, Method = method, RequestFormat = DataFormat.Json, };
restRequest.AddHeader("accept", "application/json");
restRequest.AddHeader("Authorization", credentials);
return restRequest;
}
Мой класс контроллера до сих пор выглядит следующим образом:
public async Task<IActionResult> GetMerchantSignUp()
{
await _context.ProPayResponse.ToListAsync();
return Ok();
}
Есть ли какие-либо другие шаги, необходимые для получения ответов RestSharp и представления их в моем классе контроллера?