Unable to access swagger despite cors enabled Asp.NET WebAPI

隐身守侯 提交于 2021-01-29 02:48:28

问题


I have a WebAPI - .NET framework 4.6.2 I am getting below error on the accessing the webapi via swagger:

Can't read from server. It may not have the appropriate access-control-origin settings.

I have already CORS in my code I wonder what is going worng

WebAPIConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {               
       config.EnableCors();
    }
}

GlobalAsax.cs

protected void Application_Start()
{
  RouteTable.Routes.MapOwinPath("swagger", app =>
  {
    app.UseSwaggerUi(typeof(WebApiApplication).Assembly, new SwaggerUiSettings
    {
      MiddlewareBasePath = "/swagger",
      ShowRequestHeaders = true,
      DefaultUrlTemplate = "{version}/{controller}/{action}/{id}",
      AddMissingPathParameters = true,
      Version = "v1"
    });
  });
  IModule module = TfmsModule.GetModule(typeof(MyBCModule), "My");
  module.StartModule();
  Tracer.Info("MyAPI.Application_Start: MyBCModule(\"MyAPI\").StartModule()");
  GlobalConfiguration.Configure(WebApiConfig.Register);
}

I have added below line at the start of my controller

[EnableCors(origins: "*", headers: "*", methods: "*")]

Can i get some help?


回答1:


I'm assuming you are using Swashbuckle. If this is not the case then I'll delete the post!

The error:

Can't read from server. It may not have the appropriate access-control-origin settings

is thrown when requesting the Swagger UI if the root URL does not match that of the incoming request. The root URL is used to fetch the Swagger docs by the UI page so if the root URL and the URL of the Swagger UI request differ then you hit a CORS error. As per the Swashbuckle notes:

By default, the service root url is inferred from the request used to access the docs. However, there may be situations (e.g. proxy and load-balanced environments) where this does not resolve correctly. You can workaround this by providing your own code to determine the root URL.

So there may be instances where you are coming in via a proxy and the root URL is not being set correctly. You can see the root URL that is being resolved by viewing the swagger page source and looking for the line:

window.swashbuckleConfig = {
    rootUrl: '<THE_RESOLVED_ROOT_URL>', ...

If this is different from your request URL the error you are seeing will be thrown. To fix this either use the root URL in your request or set the root URL to the one you are requesting in the SwaggerConfig.cs file:

c.RootUrl(req => GetRootUrlFromAppConfig());

...where GetRootUrlFromAppConfig is a method returning the root URL string.



来源:https://stackoverflow.com/questions/57573091/unable-to-access-swagger-despite-cors-enabled-asp-net-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!