简体   繁体   中英

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 .

Then you could use ajax or fetch api to call the web api in Razor Pages.

For example, assume Razor Pages has an original https://localhost:44304 and Web Api https://localhost:44362

1.In Web Api project startup.cs

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:

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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