【问题标题】:XMLHttpRequest Error - CORS Issue in Flutter Web(C#)XMLHttpRequest 错误 - Flutter Web 中的 CORS 问题(C#)
【发布时间】:2021-08-22 19:14:49
【问题描述】:

我在我的 c# web API 项目中启用了 CORS,如下所示:

尝试全局启用 CORS

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

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

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

和 ApiController 级别


    [EnableCors(origins:"*",headers:"*",methods:"*")]
    public class MyAppController: ApiController
    {
      [AllowAnonymous]
        [HttpGet]
        public HttpResponseMessage TestApi()
        {
        }
    }

颤动代码

 final response =
      await http.get(Uri.parse('http://localhost:44310/api/MyApp/TestApi'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return response.body;
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }

但是,两者都不起作用,并且在 Flutter Web 中仍然出现 XMLHttpRequest 错误。

此外,在“网络”选项卡中,浏览器不会针对特定 API 请求显示任何内容。

它访问 API 并从 API 发送响应,但在 Flutter Web 中未收到响应。

参考从这里为 C# Web Api 项目属性启用 CORS:https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

我错过了什么吗?

【问题讨论】:

标签: c# asp.net flutter cors flutter-web


【解决方案1】:

对于 IIS7 及更高版本:Source

只需将以下代码添加到您的 web.config。

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

对于 IIS 6,请按照以下步骤操作:Source

  1. 打开 Internet 信息服务 (IIS) 管理器
  2. 右键单击要为其启用 CORS 的站点,然后转到“属性”
  3. 更改为 HTTP 标头选项卡
  4. 在自定义 HTTP 标头部分中,单击添加
  5. 输入 Access-Control-Allow-Origin 作为标题名称
  6. 输入 * 作为标题值
  7. 点击确定两次

在 ASP.NET 上的CORS:Source

如果您无权配置 IIS,您仍然可以通过 ASP.NET 添加标头,方法是将以下行添加到您的源页面:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

其他平台请访问:Source

【讨论】:

    猜你喜欢
    • 2020-01-05
    • 2020-05-28
    • 2021-03-05
    • 2021-08-15
    • 2022-01-07
    • 2021-04-12
    • 2020-10-15
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多