简体   繁体   English

如何在相同解决方案的asp.net核心Razor页面中使用单独的asp.net核心web api

[英]How to Use separate asp.net core web api in asp.net core Razor Page in Same Solution

我使用Asp.net Core Razor Page作为我的webApp和asp.net Core api项目作为我的api服务单独...现在我如何在WebApp中使用apis ...谢谢

If the two projects have different originals, you need to enable Cross-Origin Requests (CORS) in ASP.NET Core . 如果这两个项目具有不同的原始文件,则需要在ASP.NET Core中启用跨源请求(CORS)

Then you could use ajax or fetch api to call the web api in Razor Pages. 然后你可以使用ajax或fetch api来调用Razor Pages中的web api。

For example, assume Razor Pages has an original https://localhost:44304 and Web Api https://localhost:44362 例如,假设Razor Pages有一个原始的https://localhost:44304和Web Api https://localhost:44362

1.In Web Api project startup.cs 1.在Web Api项目startup.cs

ConfigureService: ConfigureService:

services.AddCors(options =>
        {
            options.AddPolicy("MyPolicy",
            builder =>
            {
                builder.WithOrigins("https://localhost:44304")
                .AllowAnyHeader()
                .AllowAnyMethod();
            });
        });

Configure: 配置:

app.UseCors("MyPolicy");
app.UseHttpsRedirection();

2.Razor Pages Index.cshtml: 2.Razor Pages Index.cshtml:

<div>
<input type="button" value="Test"
        onclick="requestVal('https://localhost:44362/api/values')" />
<span id='result'></span>
</div>

<script>
function requestVal(uri) {
    const resultSpan = document.getElementById('result');

    fetch(uri)
        .then(response => response.json())
        .then(data => resultSpan.innerText = data)
        .catch(error => resultSpan.innerText = 'See F12 Console for error');
}
</script>

3.Click the button and display result 3.单击按钮并显示结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM