【问题标题】:An error occurred while sending the request发送请求时出错
【发布时间】:2021-05-24 09:08:30
【问题描述】:

发送请求时出错。===22/02/2021 09:14:31 - - - - - - - - - - - - - - - 堆栈跟踪 - - - - - - - - - - - - - - - - - - - - - - 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务 任务)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务)在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() 在 SingPost.NMP.Client.Internal.Areas.PPP.Controllers.TransactionController.d__1fd.MoveNext() --- 从先前抛出异常的位置结束堆栈跟踪 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务 任务)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务)在 System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.c__DisplayClass37.b__36(IAsyncResult asyncResult) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.c__DisplayClass46.b__3f() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.c__DisplayClass33.b__32(IAsyncResult asyncResult) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.c__DisplayClass21.c__DisplayClass2b.b__1c() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.c__DisplayClass21.b__1e(IAsyncResult asyncResult)===22/02/2021 09:14:31

我在从控制器调用 API 时收到上述错误消息。 控制器代码

[HttpGet]
        public async Task<ActionResult> ToEnableDisableARandRABasedonRateScheme(long mailSchemeId)
        {
            bool updated = false;
            var headerSaveUri = string.Format("{0}/{1}/{2}", ClientConstant.WEBAPI_URI_PPI_TRANSACTION, APIMETOD_TOENABLEDISABLEARANDRABASEDONRATESCHEME, mailSchemeId);
            var client = GetHTTPClient(headerSaveUri);
            HttpResponseMessage responseMessage = await client.GetAsync(headerSaveUri);
            if (responseMessage.IsSuccessStatusCode)
            {
                var responseData = responseMessage.Content.ReadAsStringAsync().Result;
                updated = JsonConvert.DeserializeObject<bool>(responseData);
            }
            return Json(updated, JsonRequestBehavior.AllowGet);
        }

HTTP 代码

public HttpClient GetHTTPClient(string uri)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(uri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ClientConstant.HTTP_TYPE));
            return client;
        }

在应用程序启动事件的 global.asax 中,我还添加了以下代码

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

【问题讨论】:

  • 如果您可以分享异常消息会很有帮助。

标签: c# asp.net-mvc api model-view-controller tcp


【解决方案1】:

控制器:

public HttpClient GetHTTPClient(string uri)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(uri);
    client.DefaultRequestHeaders.Accept.Clear();
    //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ClientConstant.HTTP_TYPE));
    return client;
}

[HttpGet]
public async Task<ActionResult> ToEnableDisableARandRABasedonRateScheme(long? mailSchemeId)
{
    bool updated = false;
    var headerSaveUri = "http://localhost:26272/";//string.Format("{0}/{1}/{2}", ClientConstant.WEBAPI_URI_PPI_TRANSACTION, APIMETOD_TOENABLEDISABLEARANDRABASEDONRATESCHEME, mailSchemeId);
    var client = GetHTTPClient(headerSaveUri);
    var uri = $"api/Values/GetTheValue/123";
    HttpResponseMessage responseMessage = await client.GetAsync(uri);
    if (responseMessage.IsSuccessStatusCode)
    {
        var responseData = responseMessage.Content.ReadAsStringAsync().Result;
        //https://stackoverflow.com/questions/22838302/deserialize-json-to-c-sharp-bool
        //string json = @"{""valid"":true}";

        var jo = JObject.Parse(responseData);
        bool flag = jo.SelectToken("updated").Value<bool>();
        updated = flag;
    }
    return Json(updated, JsonRequestBehavior.AllowGet);
}

Web.API

[Route("api/Values/GetTheValue/{partner}")]
public PassMeClass GetTheValue(string partner)
{
    Request = new HttpRequestMessage();
    Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

    Configuration = new HttpConfiguration();

    var theClinic = new PassMeClass();
    theClinic.updated = true;

    return theClinic;
}

public class PassMeClass
{
    public bool updated { get; set; }
}

【讨论】:

  • 您好 Kblau,感谢您的更新,我不认为这有什么区别,它只是通过 Accept 等属性添加标准标头的一种更简单的方法,通过 Add 方法添加自定义标头也很方便。
【解决方案2】:

尝试在以下函数中将 actionresult 更改为 jsonresult:

     [HttpGet]
    public async Task<JsonResult> ToEnableDisableARandRABasedonRateScheme(long mailSchemeId)
    {
        bool updated = false;
        var headerSaveUri = string.Format("{0}/{1}/{2}", ClientConstant.WEBAPI_URI_PPI_TRANSACTION, APIMETOD_TOENABLEDISABLEARANDRABASEDONRATESCHEME, mailSchemeId);
        var client = GetHTTPClient(headerSaveUri);
        HttpResponseMessage responseMessage = await client.GetAsync(headerSaveUri);
        if (responseMessage.IsSuccessStatusCode)
        {
            var responseData = responseMessage.Content.ReadAsStringAsync().Result;
            updated = JsonConvert.DeserializeObject<bool>(responseData);
        }
        return Json(updated, JsonRequestBehavior.AllowGet);
    }

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多