В ASP.NET Core 3.1 мне нужно использовать
Код: Выделить всё
POSTUrl:
Код: Выделить всё
https://myapi.com:6543/flexcube-customer/customer/createCustomerКод: Выделить всё
PostRequestКод: Выделить всё
HttpClientNOTE: it is ASP.NET Core 3.1.
I got this error:
Returned a failed response
in
Код: Выделить всё
var serviceResponse = await _httpProxyClient.PostRequest("FlexcubeCustomerBaseService", _createCustomerUrl, requestContentJson, "application/json");
Код: Выделить всё
fcubsheader.msgstat = "FAILURE"Код: Выделить всё
fcubsheader.msgstat = "SUCCESS"However,
Код: Выделить всё
{e.code}Код: Выделить всё
{e.message}Код: Выделить всё
Error Code: {e.code}, Message: {e.message}
From the breakpoint that I put, I see that it's getting there and returning
Код: Выделить всё
IsSuccessAlso when I consumed the API directly on POSTMAN, it returns successful response.
What am I doing incorrectly in my code?
Kindly assist to resolve this
Code:
Код: Выделить всё
appsettings.jsonКод: Выделить всё
"AppSettings": {
"FlexcubeCustomerBaseUrl": "https://myapi.com:6543/flexcube-customer/customer/createCustomer"
},
Код: Выделить всё
Startup.csКод: Выделить всё
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped();
services.AddScoped();
services.AddControllers()
.AddFluentValidation(opt =>
{
opt.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
});
// Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Service Api", Version = "v1" });
});
// Add CORS policy
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddHttpClient("FlexcubeCustomerBaseService", client =>
{
client.BaseAddress = new Uri(Configuration["AppSettings:FlexcubeCustomerBaseUrl"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
});
}
// This method gets called by the runtime. Используйте этот метод для настройки конвейера HTTP-запросов.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "Api V1" );
});
app.UseHttpsRedirection();
app.UseSerilogRequestLogging();
app.UseRouting();
// Использовать политику CORS
app.UseCors("AllowAll");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{< br /> endpoints.MapControllers();
});
}
Код: Выделить всё
ServiceResponseКод: Выделить всё
public class ServiceResponse
{
private T responseData;
public T ResponseData
{
get { return responseData; }
set { responseData = value; }
}
public HttpStatusCode StatusCode { get; set; }
public HttpResponseHeaders Headers { get; set; }
public string RequestString { get; set; }
public string ResponseString { get; set; }
public bool IsSuccessStatusCode { get; set; }
public HttpRequestMessage RequestMessage { get; set; }
}
Код: Выделить всё
HttpProxyClientКод: Выделить всё
public class HttpProxyClient : IHttpProxyClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger logger;
public HttpProxyClient(IHttpClientFactory httpClientFactory, ILogger logger)
{
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
this.logger = logger;
}
public async Task PostRequest(string name, string resourcePath, string requestContent, string mediaType)
{
logger.LogDebug($"Starting HTTP POST request to {name} at {resourcePath} with content type {mediaType}");
ServiceResponse serviceResponse = new ServiceResponse();
string response = "";
try
{
var httpClient = _httpClientFactory.CreateClient(name);
StringContent content = new StringContent(requestContent, System.Text.Encoding.UTF8, mediaType);
var result = await httpClient.PostAsync(resourcePath, content).ConfigureAwait(false);
serviceResponse.RequestMessage = result.RequestMessage;
serviceResponse.StatusCode = result.StatusCode;
serviceResponse.IsSuccessStatusCode = result.IsSuccessStatusCode;
response = await result.Content.ReadAsStringAsync();
serviceResponse.Headers = result.Headers;
logger.LogDebug($"HTTP POST response received. Status code: {result.StatusCode}");
if (result.IsSuccessStatusCode)
{
logger.LogDebug("Deserializing successful response data...");
serviceResponse.ResponseData = (T)JsonConvert.DeserializeObject(response);
}
else
{
logger.LogWarning($"HTTP POST request failed. Response: {response}");
serviceResponse.ResponseString = response;
}
}
catch (Exception ex)
{
logger.LogError($"Exception occurred during HTTP POST request: {ex.Message}");
serviceResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError;
serviceResponse.IsSuccessStatusCode = false;
serviceResponse.ResponseString = $"Exception: {ex.Message} | Response: {response}";
}
logger.LogDebug($"Exiting HTTP POST request method. Ответ: {response}");
return serviceResponse;
Код: Выделить всё
public class CreateCustomerRequest
{
[JsonProperty("customerType")]
public string CustomerType { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("addressLine1")]
public string AddressLine1 { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
public override string ToString()
{
return $"name: {FullName}| ph: {MobileNumber}";
}
}
Код: Выделить всё
public class FlexcubeCreateCustomerResponse
{
public FcubsheaderCustomer fcubsheader { get; set; }
public FcubsbodyCustomer fcubsbody { get; set; }
}
public class CustomerFull
{
public object privatecustomer { get; set; }
public string custno { get; set; }
public string ctype { get; set; }
public string name { get; set; }
public string nlty { get; set; }
}
public class FcubsbodyCustomer
{
public CustomerFull customerFull { get; set; }
public List fcubserrorresp { get; set; }
public List fcubswarningresp { get; set; }
}
public class FcubsheaderCustomer
{
public string source { get; set; }
public object multitripid { get; set; }
public string functionid { get; set; }
public string action { get; set; }
public string msgstat { get; set; }
public object finalreq { get; set; }
public object snapshotid { get; set; }
public object password { get; set; }
public object addl { get; set; }
}
public class FcubswarningrespCustomer
{
public List warning { get; set; }
}
public class FcubserrorrespCustomer
{
public List error { get; set; }
}
public class WarningCustomer
{
public string wcode { get; set; }
public string wdesc { get; set; }
}
public class ErrorCustomer
{
public string code { get; set; }
public string message { get; set; }
}
Код: Выделить всё
public class FlexcubeAccountService : IFlexcubeAccountService
{
private readonly ILogger _logger;
private readonly IHttpProxyClient _httpProxyClient;
private readonly string _createCustomerUrl;
public FlexcubeAccountService(
ILogger logger,
IHttpProxyClient httpProxyClient,
IConfiguration configuration
)
{
_logger = logger;
_httpProxyClient = httpProxyClient;
_createCustomerUrl = configuration["AppSettings:FlexcubeCustomerBaseUrl"];
}
public async Task CreateCustomer(CreateCustomerRequest createCustomerRequest)
{
var customerDetails = new FlexcubeCreateCustomerResponse();
var requestContent = new CreateCustomerRequest
{
CustomerType = createCustomerRequest.CustomerType,
Name = createCustomerRequest.Name,
AddressLine1 = createCustomerRequest.AddressLine1,
Country = createCustomerRequest.Country
};
string requestContentJson = JsonConvert.SerializeObject(requestContent);
var serviceResponse = await _httpProxyClient.PostRequest("FlexcubeCustomerBaseService", _createCustomerUrl, requestContentJson, "application/json");
if (serviceResponse.IsSuccessStatusCode)
{
if (serviceResponse.ResponseData.fcubsheader.msgstat == "SUCCESS")
{
customerDetails = serviceResponse.ResponseData;
if (serviceResponse.ResponseData.fcubsbody.fcubswarningresp != null && serviceResponse.ResponseData.fcubsbody.fcubswarningresp.Any())
{
foreach (var предупреждение в serviceResponse.ResponseData.fcubsbody.fcubswarningresp)
{
foreach (var w in alert. предупреждение)
{
_logger.LogInformation($"Код успеха: {w.wcode}, Описание: {w.wdesc}");
else
{
_logger.LogWarning("CreateCustomer({createCustomerRequest}) вернул неверный ответ {FlexcubeCreateCustomerResponse}", createCustomerRequest, serviceResponse.ResponseData);
if (serviceResponse.ResponseData.fcubsbody.fcubserrorresp != null && serviceResponse.ResponseData.fcubsbody.fcubserrorresp.Any())
{
foreach (ошибка var в serviceResponse.ResponseData.fcubsbody.fcubserrorresp)
{
foreach (var e in error.error)
{
_logger.LogError($"Не удалось создать учетную запись клиента. Ошибка: {serviceResponse.ResponseData?.fcubsheader.msgstat}");
_logger.LogError($"Не удалось создать учетную запись клиента. Код ошибки: {e.code}, Сообщение: {e.message}");
else
{
_logger.LogWarning("CreateCustomer({createCustomerRequest}) возвратил неверный ответ с кодом состояния. s: {statusCode} e: {errorString}", createCustomerRequest, serviceResponse.StatusCode, serviceResponse.ResponseString);
return null;
return customerDetails;< br /> }
}
Источник: https://stackoverflow.com/questions/781 ... re-web-api