处理Web API状态代码的最佳实践

时间:2017-07-02 16:09:26

标签: rest asp.net-web-api asp.net-core restsharp asp.net-core-webapi

我有一个使用.NETCore完成的Web API项目。

我的网络API收到来自其他服务A的请求,我需要的信息需要对数据进行一些转换并将其发送给另一个服务B.

我期待服务B发回一些回复:如OK或NOK。由于我可以从服务B获得的代码数量如此之多。我想知道处理这些代码的最佳做法是什么?

正如您将在我的代码中看到的那样,我以这种方式获取状态代码:

var status = (int)response.StatusCode;

我有一些如果要处理这个问题。看看我的代码,它看起来像一个非常差的状态代码处理,但目前它是我能做的最好的。我很乐意提出改进建议。

我正在使用RestSharp。 按照我的代码:

    [HttpPost]
    [Produces("application/json", Type = typeof(MyModel))]
    public async Task<IActionResult> Post([FromBody]MyModel myModel)
    {
         try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var response = (RestResponse) await _restHelper.GetResponse("ServiceB:url", myModel);

            if (response != null)
            {
                var status = (int)response.StatusCode;

                //2xx status OK
                if (status >= 200 && status < 300)
                {
                    return Ok(response.Content);
                }

                //Catch all status code
                return StatusCode(status, response.Content);
            }

            //If for some reason, I don't get any response from ServiceB
            return NotFound("No response from ServiceB");
        }
        catch (Exception ex)
        {
            _logger.LogError("POST_ERROR", "ServiceB-relay/Post UNEXPECTED ERROR", ex.Message);
            return StatusCode(500, "Server error, not able to process your request");
        }
    }

这是我的restHelper

    public class RestHelper: IRestHelper
    {
        private readonly IConfigurationRoot _config;

        public RestHelper(IConfigurationRoot config)
        {
            _config = config;
        }

        public async Task<IRestResponse> GetResponse(string configKey, object dtoObject)
        {
            //Get the URL from the config.json
            var url = _config[configKey];

            //Create rest client and rest request
            var restClient = new RestClient(url);
            var request = new RestRequest {Timeout = 30000, Method = Method.POST};

            //Add header
            request.AddHeader("Accept", "application/json");

            //convert the dto object to json
            var jsonObject = JsonConvert.SerializeObject(dtoObject.ToString(), Formatting.Indented);
            request.AddParameter("application/json", jsonObject, ParameterType.RequestBody);

            var taskCompletion = new TaskCompletionSource<IRestResponse>();

            //Execute async
            restClient.ExecuteAsync(request, r => taskCompletion.SetResult(r));

            //await the task to finish
            var response = (RestResponse) await taskCompletion.Task;

            return response;
        }

由于

0 个答案:

没有答案