【问题标题】:webapi cors error in HttpPost method in webapiwebapi中的HttpPost方法中的webapi cors错误
【发布时间】:2021-01-12 13:45:33
【问题描述】:

我正在使用 WebAPI 服务器和 javascript 客户端。 我在 webapi 中有以下代码可以正常工作

    [EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        [Route("Controller/ConditionFiles")]
        [HttpGet]
        public async Task<IHttpActionResult> GetConditionFiles()
        {
            var files = await Task.Run(() => new DirectoryInfo(workingFolder).GetFiles().Select(o => o.Name.Replace(".csv","")).ToArray());
            return Ok(files);

        }

但是下面的代码(HttpPost)不起作用

[EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        [Route("Controller/MultiComplexity")]
        [HttpPost]
        public async Task<IHttpActionResult> GetMultiComplexity()
        {
            var vlFileNamesList=new List<string>();
            var vlFileContents=new List<string>();
            var result = await Request.Content.ReadAsMultipartAsync();
            var processFile = result.Contents[0].ReadAsStringAsync().Result;
            var length = Convert.ToInt32(result.Contents[1].ReadAsStringAsync().Result);
            var closeVias = result.Contents[2].ReadAsStringAsync().Result;
            int i=3;
            for(i=3;i<length+3;i++)
            {
                vlFileNamesList.Add(result.Contents[i].ReadAsStringAsync().Result);
            }
            for(;i<2*length+3;i++)
            {
                vlFileContents.Add(result.Contents[i].ReadAsStringAsync().Result);
            }

            var closeViasBool = closeVias == "true";
            if (processFile != "")
            {
                var process = File.ReadAllText(workingFolder + processFile + ".csv");
                var vlFileAnalyzer = new MultiVLFiles.MultiVLFiles_class();
                //return Ok(new ABC() { a = vlFileContents.ToArray(), b = vlFileNamesList , c=process});
                bool isError=false;
                var complexity = await Task.Run(() => vlFileAnalyzer.getFinalComplexity(vlFileContents.ToArray(), vlFileNamesList, process, closeViasBool, "NA", "NA", isError));
                return Ok(complexity);
            }
            return Ok("No Process was selected");
        }

并返回以下错误 对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。httppost

我的 web.config 有以下部分

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:8080" />
      </customHeaders>

另外,我安装了 cors(来自 nuget)并在 WebApiConfig.cs 文件中有以下行-

    config.EnableCors();

可能是什么问题?我该如何解决?

【问题讨论】:

  • 谁能帮忙?

标签: javascript html asp.net-web-api cors asp.net-web-api2


【解决方案1】:

我假设您正在使用带有 web api 的最新版本的 dot net core。

首先,我强烈建议您从头开始,因为您做了很多可能与下面提供的正确步骤发生冲突的事情。

添加 CORS(在最新版本中)很简单,分两步完成。

第 1 步 - 配置服务

        //lets add some CORS stuff 
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder => {
                builder.WithOrigins(tempConfigHelperStuff.AddCorsOrigin1LocalHost,
                                    tempConfigHelperStuff.AddCorsOrigin2ProductionSite,
                                    tempConfigHelperStuff.AddCorsOrigin3DevOrTestOrSomethingElseSite);
                builder.AllowAnyMethod();
                builder.AllowAnyHeader();
                builder.AllowCredentials();
            });
        });

注意:WithOrigins(tempConfigHelperStuff.AddCorsOrigin1LocalHost, 在这里,“tempConfigHelperStuff.AddCorsOrigin1LocalHost”只是一些字符串,如“www.something.com”或“localhost:PORTNUMBER”,您正在运行您的网络应用程序或其他东西。 第 2 步 - 配置

        app.UseCors();

最后,根据我的经验,将这些代码行放在哪里也很重要。我有一个带有此代码的工作演示服务器代码,可以正常工作

https://github.com/Jay-study-nildana/RandomStuffGenerator/blob/master/RandomStuffGeneratorPrivate/RandomStuffGeneratorPrivate/Startup.cs

【讨论】:

    猜你喜欢
    • 2014-10-27
    • 2021-07-27
    • 2023-03-16
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多