У меня есть следующий веб-API, самозачищенный:
public class ApiShell : IApiShell
{
private IActorSystemSettings _settings;
public ApiShell(IActorSystemSettings settings)
{
_settings = settings;
}
IDisposable _webApp;
public void Start()
{
_webApp = WebApp.Start<Startup>(_settings.SystemUrl);
Console.WriteLine($"Web server running at '{_settings.SystemUrl}'");
}
public void Stop()
{
_webApp.Dispose();
}
internal class Startup
{
//Configure Web API for Self-Host
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.EnableCors();
config.MapHttpAttributeRoutes();
//default route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
config
.EnableSwagger(c => c.SingleApiVersion("v1", "Web API"))
.EnableSwaggerUi();
app.UseWebApi(config);
config.DependencyResolver = new AutofacWebApiDependencyResolver(IoC.Container);
}
}
}
Как только я хочу включить Cors, добавив следующую строку, config.EnableCors(); мой веб-API больше не доступен через Swagger, и я получаю следующий ответ:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.HttpRouteCollection.GetRouteData(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.HttpServer.<SendAsync>d__24.MoveNext()
</StackTrace>
</Error>
Я попытался установить HttpConfiguration.EnsureInitialized(), но это привело к следующей ошибке:
Could not load file or assembly 'System.Web.Cors, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.'
Я установил следующую версию Microsoft.AspNet.WebApi.Cors
Install-Package Microsoft.AspNet.WebApi.Cors.cs -Version 5.2.3
Как я могу включить CORS в моем веб-API?





Вы забыли указать AppBuilder использовать cors.
Попробуйте добавить следующую строку в метод конфигурации запуска
app.UseCors(CorsOptions.AllowAll);
@monstertjie_za только что понял, что эти параметры взяты из Microsoft.Owin.Cors. Если вы не используете Owin, просто забудьте об этом
вы можете включить корс по следующему образцу
using System.Web.Http;
using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EvalSamplesController : ApiController
{
[HttpGet]
public List<EvalSamplesViewModel> GetHeaderList()
{
List<EvalSamplesViewModel> simpleModel = obj.ReadAllList();
return simpleModel;
}
}
и в app_start в WebApiConfig поместите следующую строку в метод Register
public static void Register(HttpConfiguration config)
{
config.EnableCors();
/////////
}
В каком пространстве имен это находится?