将简单的HTML前端连接到使用c#构建的API



我用c#构建了一个API,当我执行"Get"从邮递员。

现在,我试图执行相同的"Get"使用我正在构建的HTML网页。

这是我到目前为止的HTML:

<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<script>
const Http = new XMLHttpRequest();
const url='https://localhost:44369';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
console.log(Http.responseText)
}
</script>
</body>
</html>

这是我的API中我要执行的方法"Get":

//https://localhost:44369/api/Request
[EnableCors("AllowLocalhostOrigins")]
[HttpGet]
public ActionResult GetText()
{

string a = "b";
return Ok(a);
}

这里是错误:

从源'null'访问'https://localhost:44369/'的XMLHttpRequest已被CORS策略阻止:请求的资源上没有'Access- control - allow - origin '标头。

我已经读过CORS,但我不清楚我需要在HTML中做什么才能使它工作。API返回"Get"请求在邮差中很好,所以我知道API至少能正常工作。

您需要在API中设置CORS策略。请看这个问题->如何在ASP中启用CORS。可接受的答案有MSDN文档的链接。

你也可以在这里找到一个很好的教程->c# Corner Cors教程

你的前端正在从一个特定的URL调用。您的API根据其关于调用它的url的策略(CORS)决定是否要授予该请求。

为了进一步澄清,如果你的前端应用程序中没有bug,那么就没有什么可以阻止你调用API。API告诉它"不"因为API没有配置为接受来自前端URL的请求。

编辑

根据Mason在下面的评论中给出的非常有用的信息,关于如何使用CORS设置权限,我是错误的。当您在API中配置CORS时,它是API提供给浏览器的基于头的系统。你的浏览器知道它是一个可信的来源,它将允许来自托管API的服务器的信息加载到浏览器中。浏览器允许API,而不是API允许从浏览器调用。

将Startup.cs文件更改为以下内容后,我不再得到"被CORS策略错误阻止的访问"。

public void ConfigureServices(IServiceCollection services)
{
/* I added */
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
//.AllowCredentials();
});
});
services.AddControllers();           
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}          
app.UseHttpsRedirection();
app.UseRouting();
/* I added */
app.UseCors();

最新更新