ASP.NET Core Web API-如何将指定字段作为有效载荷传递给第三方API

发布于 2025-02-08 09:24:14 字数 3834 浏览 1 评论 0原文

我在ASP.NET Core-6 Web API中有第三方API

做到了:

appSettings.json:

  "Endpoints": {
    "EmployeeUrl": "http://api.thirdpartycompany.com:2233/api/EmployeeDetail"
  }

DTO:

public class EmployeeDataRequest
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmployeeCode { get; set; }

    public decimal Salary { get; set; }

    public string Location { get; set; }

    public string Email { get; set; }
}

服务:

public class EmployeeService : IEmployeeService
{
    private readonly HttpClient _httpClient;
    private readonly HttpHelper _httpHelper;
    private readonly IConfiguration _config;
    private readonly IUnitOfWork _unitOfWork;
    private readonly string baseUrl;

    public EmployeeService(
        HttpClient httpClient,
        HttpHelper httpHelper,
        IUnitOfWork _unitofwork,
        )
    {
        _httpClient = httpClient;
        _httpHelper = httpHelper;
        _config = config;
        _unitOfWork = _unitofwork;
        baseUrl = config.GetSection("Endpoints").GetValue<string>("baseUrl");
    }

    public async Task<BaseResponse> EmployeeDetail(EmployeeDataRequest payload)
    {
        var response = new BaseResponse();
        using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            try
            {
                var employee = new Employee
                {
                    FirstName = payload.FirstName,
                    LastName = payload.LastName,
                    EmployeeCode = payload.EmployeeCode,
                    Salary = payload.Salary
                    Location = payload.Location,
                    Salary = payload.Salary,
                    Email = payload.Email
                };
                await _unitOfWork.Employees.InsertAsync(employee);
                await _unitOfWork.Save();

                var headers = new Dictionary<string, string>();
                headers.Add("Authorization", $"Bearer {token.access_token}");

                var employeeEndPoint = baseUrl + _config.GetSection("Endpoints").GetValue<string>("EmployeeUrl");
                var httpResponse = _httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: payload, headers: headers).Result;
                if (httpResponse != null)
                {
                    if (httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        response = JsonConvert.DeserializeObject<EmployeeDataResponse>(content);
                    }
                    else
                    {
                        response = new BaseResponse { ResponseCode = httpResponse.StatusCode.ToString(), ResponseDescription = httpResponse.ReasonPhrase };
                    }
                }
                transaction.Complete();
            }
            catch (Exception ex)
            {
                response = new BaseResponse { response_code = "96", response_description = "Error occured, contact admin" };
            }
            return response;
        }
    }
}

我想将数据插入数据库(员工表),然后将某些字段作为有效载荷传递给第三方API(雇员)。

从上面的 hospereedetail 服务中,我成功地将所有字段插入员工表中,并将所有雇都有的字段作为有效载荷中的所有字段,如 httpresponse 所做的那样,作为 有效载荷

但是,我想将这些字段(薪水和位置)排除到第三方API(我只想将它们插入员工表中)。但是通过其他字段(名称,姓氏,imhereeecode和电子邮件)。

我该如何实现?

谢谢。

I have this third party api in ASP.NET Core-6 Web API

http://api.thirdpartycompany.com:2233/api/EmployeeDetail

So, I did this:

appsettings.json:

  "Endpoints": {
    "EmployeeUrl": "http://api.thirdpartycompany.com:2233/api/EmployeeDetail"
  }

DTO:

public class EmployeeDataRequest
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmployeeCode { get; set; }

    public decimal Salary { get; set; }

    public string Location { get; set; }

    public string Email { get; set; }
}

Service:

public class EmployeeService : IEmployeeService
{
    private readonly HttpClient _httpClient;
    private readonly HttpHelper _httpHelper;
    private readonly IConfiguration _config;
    private readonly IUnitOfWork _unitOfWork;
    private readonly string baseUrl;

    public EmployeeService(
        HttpClient httpClient,
        HttpHelper httpHelper,
        IUnitOfWork _unitofwork,
        )
    {
        _httpClient = httpClient;
        _httpHelper = httpHelper;
        _config = config;
        _unitOfWork = _unitofwork;
        baseUrl = config.GetSection("Endpoints").GetValue<string>("baseUrl");
    }

    public async Task<BaseResponse> EmployeeDetail(EmployeeDataRequest payload)
    {
        var response = new BaseResponse();
        using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            try
            {
                var employee = new Employee
                {
                    FirstName = payload.FirstName,
                    LastName = payload.LastName,
                    EmployeeCode = payload.EmployeeCode,
                    Salary = payload.Salary
                    Location = payload.Location,
                    Salary = payload.Salary,
                    Email = payload.Email
                };
                await _unitOfWork.Employees.InsertAsync(employee);
                await _unitOfWork.Save();

                var headers = new Dictionary<string, string>();
                headers.Add("Authorization", 
quot;Bearer {token.access_token}");

                var employeeEndPoint = baseUrl + _config.GetSection("Endpoints").GetValue<string>("EmployeeUrl");
                var httpResponse = _httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: payload, headers: headers).Result;
                if (httpResponse != null)
                {
                    if (httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        response = JsonConvert.DeserializeObject<EmployeeDataResponse>(content);
                    }
                    else
                    {
                        response = new BaseResponse { ResponseCode = httpResponse.StatusCode.ToString(), ResponseDescription = httpResponse.ReasonPhrase };
                    }
                }
                transaction.Complete();
            }
            catch (Exception ex)
            {
                response = new BaseResponse { response_code = "96", response_description = "Error occured, contact admin" };
            }
            return response;
        }
    }
}

I want to insert the data into the Database (Employee Table), and then pass some of the fields as payload to the third party API (EmployeeUrl).

From EmployeeDetail Service above, I successfully inserted all the fields into Employee table and passed all the fields in EmployeeDataRequest as payload into the third party api as done in httpResponse as payload

However, I want to exclude these fields (Salary and Location) from going into the third party api (I only want to insert them into the Employee table). But pass the other fields (FirstName, LastName, EmployeeCode and Email).

How do I achieve this?

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时光的容颜 2025-02-15 09:24:14

您创建一个接口,该接口包含与第三方关联的属性

  public interface IEmployeeDataRequestForThirdParty
    {
        string FirstName { get; set; }

        string LastName { get; set; }

        string EmployeeCode { get; set; }

        string Email { get; set; }
    }

 public class EmployeeDataRequest : IEmployeeDataRequestForThirdParty
    {
        public string FirstName { get; set; };

        public string LastName { get; set; };

        public string EmployeeCode { get; set; };

        public decimal Salary { get; set; };

        public string Location { get; set; };

        public string Email { get; set; };
    }

,然后将其发送到您的帖子,您可以施放您的帖子

_httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: (IEmployeeDataRequestForThirdParty) payload, headers: headers).Result;

,以便将对象序列化,仅与接口的暴露属性序列化。

我尚未测试过这一点,但是这种方法应该起作用,另一个选择是您可以创建第三方的基类,然后您可以从opplyeedatarequest继承

you create an interface that contains the properties associated to 3rd party

  public interface IEmployeeDataRequestForThirdParty
    {
        string FirstName { get; set; }

        string LastName { get; set; }

        string EmployeeCode { get; set; }

        string Email { get; set; }
    }

 public class EmployeeDataRequest : IEmployeeDataRequestForThirdParty
    {
        public string FirstName { get; set; };

        public string LastName { get; set; };

        public string EmployeeCode { get; set; };

        public decimal Salary { get; set; };

        public string Location { get; set; };

        public string Email { get; set; };
    }

before sending it to your post you can cast

_httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: (IEmployeeDataRequestForThirdParty) payload, headers: headers).Result;

so the object would be serialized with only exposed properties from the interface.

I have not tested this, but this approach should work, the other option would be you could create a base class of 3rd party then you can inherit from EmployeeDataRequest

月野兔 2025-02-15 09:24:14

如果opplyeedatarequest可以假定您的应用程序中使用的DTO作为内部服务调用,当您的employservice的方法被调用,则您不应将其传递给外部派对。

而是从homplyeedatarequest dto映射到thirdpartyemployeedetail dto。
这是将每个DTO的用法解除。

因此,如果将来,opplyeedatarequest dto需要一个新的hirseeposition属性,它将不会影响您的第三方API呼叫。

创建一个类:

public class ThirdPartyEmployeeDetail
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmployeeCode { get; set; }

    public string Email { get; set; }
}

然后,映射并致电您的第三方API。

var apiPayLoad = new ThirdPartyEmployeeDetail()
{
    FirstName = payload.FirstName,
    LastName = payload.LastName,
    EmployeeCode = payload.EmployeeCode,
    Email = payload.Email
};

var httpResponse = _httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: apiPayLoad , headers: headers).Result;

映射本身,如果要在您的其他API调用到第三方塞里西斯的其他API呼叫上重复,则可以将逻辑提取到另一个类中以转换并返回thirdpartyemployeedeedetailoployeedaTareAtareQuest >作为参数传递。

If EmployeeDataRequest can be assumed to be a DTO used within your application as an internal service call when your EmployeeService's methods are called, then you should not pass it to the external party.

Instead, map from EmployeeDataRequest DTO to ThirdPartyEmployeeDetail DTO.
This is to decouple the usage of each DTO.

So if in the future, EmployeeDataRequest DTO needs a new EmployeePosition property, it will not affect your 3rd party API call at all.

Create a class:

public class ThirdPartyEmployeeDetail
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmployeeCode { get; set; }

    public string Email { get; set; }
}

Then, map and call your 3rd party API.

var apiPayLoad = new ThirdPartyEmployeeDetail()
{
    FirstName = payload.FirstName,
    LastName = payload.LastName,
    EmployeeCode = payload.EmployeeCode,
    Email = payload.Email
};

var httpResponse = _httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: apiPayLoad , headers: headers).Result;

The mapping itself, if it is going to be repeated on your other API calls to the 3rd party sercice, you may extract the logic into another class to convert and return ThirdPartyEmployeeDetail when EmployeeDataRequest is passed as a parameter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文