c# - 调用 httpClient.PostAsync 返回 null

标签 c# .net api

我正在尝试调用一个 api,实习生调用外部 api 获取数据。我写的代码是:

    [HttpPost]
    public IHttpActionResult Post()
    {

        string _endpoint = "https://someurl.com/api/v1/models?auth_token=mytoken";
        var httpContext = (System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"];
        string upload_id = httpContext.Request.Form["upload_id"];
        string filename =  httpContext.Request.Form["filename"];
        string filesize = "1000";


        //return this.Ok<string>(upload_id + " " + filename);         


        var content = new FormUrlEncodedContent(new[] 
        {
            new KeyValuePair<string, string>("upload_id", upload_id),
            new KeyValuePair<string, string>("filename", filename),
            new KeyValuePair<string, string>("filesize", filesize)
        });  

        using (var httpClient = new HttpClient())
        {
            var response = httpClient.PostAsync(_endpoint, content).Result;
            return Json(JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result));
        }



    }

客户端然后我通过ajax调用来获取数据:

$.ajax({
        url: '/api/tws',
        type: 'POST',
        data: { 'file': "EX-IGES.IGS", 'upload_id': "eb550576d2" },
        success: function (response) { 
                 console.log('response',response);
                 }
 });

但是它总是返回空值。我已验证 API 调用有效并且一切正确。我对 C# 有点陌生。

最佳答案

查看您在参数"file"中传递的 ajax 调用,但在 C# 中您正在寻找“文件名”

固定ajax代码:

$.ajax({ url: '/api/tws', 
       type: 'POST', 
       data: { 'filename': "EX-IGES.IGS", 'upload_id': "eb550576d2" }, 
       success: function (response) { console.log('response',response); } 
 });

关于c# - 调用 httpClient.PostAsync 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27517009/

相关文章:

c# - 打开使用 EPPlus 创建并使用 ICSharpCode.SharpZipLib 压缩到文件夹中的 .xlsx 文件时出现问题

c# - 富文本框超链接

api - YouTube Data API playlistItems :List only returns max of 100 data items - or 2 pages of data, 工作正常 7 月 16 日

c# - 从纯 C 程序调用的 DLL 函数(在 C# .NET 中)导致错误

面向 Clojure 用户的 Java

ruby-on-rails - 带有葡萄的 Rails 中仅 API 的应用程序?

c# - 你会在长开关/枚举声明中使用区域吗?

javascript - 从隐藏的代码中过滤 TextBox 的 KeyPress 事件上的 GridView

c# - 将 HTML 放入 Html.ActionLink() 中,加上没有链接文本?

.net - 国际奥委会最佳实践: How to best manage dependency graph?