【问题标题】:JavaScript fetch call returning empty string when calling ASP.Net WebAPI endpoint调用 ASP.Net WebAPI 端点时,JavaScript 获取调用返回空字符串
【发布时间】:2020-10-18 13:37:09
【问题描述】:

我很困惑为什么我的 c# WebAPI 调用无法从 JavaScript 中获取并且总是返回一个空字符串。

这是我在 C# API 控制器中的方法

    [AllowAnonymous]
    [Route("GetApiExample")]
    [HttpPost]
    public IHttpActionResult GetApiExample()
    {
        return Ok(new { success = true });
    }

这是我的 javascript

fetch('https://localhost:44363/api/Example/GetApiExample', {
  method: 'POST',
  mode: 'no-cors',
})
  .then((response) => response.text())
  .then((json) => console.log(json));

我假设它一定是 c# 方面的东西,或者事实是它需要 no-cors。

有人有什么想法吗?

** 更新 **

我已经更新到下面的答案,但这仍然会带回一个空字符串

【问题讨论】:

    标签: javascript c# webapi


    【解决方案1】:

    它应该是在参数中序列化的对象,而不是字符串。此外,您的代码中有 3 个“c”字母代表“succcess”。

     public IHttpActionResult GetApiExample()
     {    
         return Ok(new { success = true });
     }
    

    更新:

    mode: 'no-cors'
    

    这并不完全允许来自浏览器的 cors 请求。浏览器将始终拒绝对其他域名的 http 请求,除非该目标域启用了 CORS。 'no-cors' 只是禁用检查跨域的选项。如果您在两个项目之间使用不同的端口号,则必须通过启用 CORS 在您的 api 项目中启用 Access-Control-Allow-Origin 标头。

    【讨论】:

    • 感谢您的回复,我已经更新了代码,但这仍然带回一个空字符串
    • @user3284707 您是否检查了浏览器控制台和网络部分并确保响应存在并且您没有任何 HTTP 错误??
    • 嗨,是的,我已经检查过了,它的状态为 200
    • @user3284707 您还应该根据此处将 response.text() 更改为 response.json() :developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
    • 我最初有这个,但它出现了一个解析错误,这就是为什么我把它放到文本中以查看响应是什么。 “未捕获(承诺)SyntaxError:输入意外结束”
    【解决方案2】:

    您可以像这样使用 ajax 发布请求。

    $.ajax({
        type: 'POST',
        url: 'url',
        crossDomain: true,
        data: '{}',
        dataType: 'json',
        success: function(data, textStatus, jqXHR) {
            var value = data;
        },
        error: function (data, textStatus, errorThrown) {
            //Handle error
        }
    });
    

    【讨论】:

    • 谢谢,我已经试过了,最后是服务器端没有正确设置CORS,我已经添加了解决方案作为答案
    【解决方案3】:

    最后的答案是服务器端没有正确启用CORS

    https://stackoverflow.com/a/54800308/3284707

    我需要将以下内容添加到我的 WebApiConfig

    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);
    

    完整的代码是这样的……

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
    
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
        }
    }
    

    然后我的 javascript 删除模式:no-cors

    fetch('https://localhost:44363/api/Example/GetApiExample', {
      method: 'POST',
    })
      .then((response) => response.json())
      .then((json) => console.log(json));
    

    【讨论】:

      猜你喜欢
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 2012-10-27
      相关资源
      最近更新 更多