dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.19k stars 9.93k forks source link

Error when trying get data from real server #16361

Closed Gyciauskas closed 4 years ago

Gyciauskas commented 6 years ago

Hello,

I have issue with this code from demo:

@page "/fetchdata"
@inject HttpClient Http

@if (door == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class='table'>
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Version</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>@door.id</td>
                <td>@door.name</td>
                <td>@door.version</td>
            </tr>
        </tbody>
    </table>
}

@functions {
    Door door;

    protected override async Task OnInitAsync()
    {
        door = await Http.GetJsonAsync<Door>("http://localhost:58009/api/locations/1/doors/2");
    }

    class Door
    {
        public int id { get; set; }
        public int? locationId { get; set; }
        public string name { get; set; }
        public int strikeTime { get; set; }
        public int extendedAccessTime { get; set; }
        public int heldOpenTime { get; set; }
        public string version { get; set; }
    }
}

I'm getting error in browser console window:

SEC7120: Origin http://localhost:5375 not found in Access-Control-Allow-Origin header.

WASM: [System.Net.Http.HttpRequestException] TypeError: Failed to fetch

4 WASM: --- End of stack trace from previous location where exception was thrown ---

If I just simply request if in browser => "http://localhost:58009/api/locations/1/doors/2", I get this json response: { "id":2, "locationId":1, "name":"216office", "strikeTime":3, "extendedAccessTime":6, "heldOpenTime":10, "version":"AAAAAAAAKMw=" }

It is possible that need setup header content type to "application/json"?

floreseken commented 6 years ago

It's a CORS config problem

Add this to your startup.cs:

 public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
...

And

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseCors("CorsPolicy");

On the server side

Gyciauskas commented 6 years ago

Ok, thanks!

But is Blazor app, service can't find such extension method...

Error CS1061 'IServiceCollection' does not contain a definition for 'AddCors' and no extension method 'AddCors' accepting a first argument of type 'IServiceCollection' could be found

using Microsoft.AspNetCore.Blazor.Browser.Rendering;
using Microsoft.AspNetCore.Blazor.Browser.Services;

namespace BlazerTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            var serviceProvider = new BrowserServiceProvider(configure =>
            {
                configure.AddCors(options =>
                {
                    options.AddPolicy("CorsPolicy",
                        builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
                });
            });

            new BrowserRenderer(serviceProvider).AddComponent<App>("app");
        }
    }
}

So I need this class: CorsMiddlewareExtensions. Which is in Microsoft.AspNetCore.Builder. Trying seach and add via nuget manager, but no success

liamehenderson commented 6 years ago

You need Microsoft.AspNetCore.Cors

https://www.nuget.org/packages/Microsoft.AspNetCore.Cors/

floreseken commented 6 years ago

The problem is server side. It just surfaces as a client problem...

danroth27 commented 6 years ago

@Gyciauskas To enable CORS you need to update the server project (not the client Blazor project). See https://docs.microsoft.com/en-us/aspnet/core/security/cors for details on how to enable CORS in ASP.NET Core.

Gyciauskas commented 6 years ago

Yes, it finally working! Thank you guys! Now the fun part begins

danroth27 commented 6 years ago

🎉 🎆 :tada: :smile:

Pat28 commented 6 years ago

@Gyciauskas how did you solve the issue? I am struggling with the same thing, did the stuff in Blazor to AddCors() and AddPolicy etc... But were to tell to use that policy? Or is it still a server side issue? I am using IISExpress from Visual Studio and even that won't let me do a request to any website/page.

tusharparik commented 5 years ago

Same Issue with me post hosting it on IIS the data in table is not fetched and Console says

blazor.webassembly.js:1 GET http://*.*.*.*:99/api/Employee/Index 500 (Internal Server Error)

blazor.webassembly.js:1 WASM: at BlazorAppHosted.Client.Pages.FetchEmployee.OnInitAsync () <0x1c99308 + 0x000d0> in :0

jbarrineau06 commented 5 years ago

I'm having the same issue, but I can't call UseCors() in the Startup.Configure method because it takes an IBlazorApplicationBuilderand not an IApplicationBuilder.

Suchiman commented 5 years ago

@jbarrineau06 as mentioned previously, CORS need to be enabled on the server side, not in blazor (CORS is about security so the server must permit the browser to call it)

jbarrineau06 commented 5 years ago

@Suchiman I'm using the Blazor project template, not the Blazor (ASP.NET Core hosted) project template, how would I do this there where I don't have the separate Client and Server projects?

Suchiman commented 5 years ago

@jbarrineau06 who is providing the Service you're trying to call? The provider of the service must enable CORS

jbarrineau06 commented 5 years ago

@Suchiman This is just a localhost project

Suchiman commented 5 years ago

@jbarrineau06 that localhost project needs to enable CORS Http.GetAsync("http://localhost:12345") this-----------------------^^^^^^^^^^ project needs to enable CORS

wcolorless commented 5 years ago

Is it not possible to include Cors in an application template without a server? Then he is not so interesting. This is a big problem.