SCENARIO:
I have two applications, one is "SPA web application" and the other one is "Web API 2.0" which is deployed on IIS 8.0 on Windows Server 2012.
ERROR:
Website is accessible and working fine on the same machine but not from outside, web page is loaded properly but on ajax call to the API generates the following error...
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . This can be fixed by moving the resource to the same domain or enabling CORS.
On controller level I have added the following attribute:
[EnableCors(origins: "", headers: "", methods: "*", SupportsCredentials = true)]
Also enabled it in WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "DefaultAction" }
);
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
}
web.config server configuration is like this..
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
and following is the snippet of the ajax call..
$.ajax({
type: 'get',
url: webApiUrl,
success: function (response) {
// some logic here
},
error: function (response) {
// some logic here
},
xhrFields: {
withCredentials: true
},
crossDomain: true
});
FURTHER DETAILS:
I have deployed the same website on IIS 7.5 on a Windows Server 2008 R2 and it is working fine without any issue.
Secondly I have also tried by adding following response headers in IIS 8..
Access-Control-Allow-Headers - Content-Type
Access-Control-Allow-Methods - POST,GET,OPTIONS
Also tried to change following value in web.config
to
None of these have worked for me so far. Looking for further help...
FIXED :: That was just the firewall blocking the hosted web api port :(
just the firewall blocking the hosted web api port
Related
Program.cs
using MediatR;
using Microsoft.AspNetCore.Authentication.Negotiate;
using System.Reflection;
using WindowsProxy.Interfaces;
using WindowsProxy.Services;
var builder = WebApplication.CreateBuilder(args);
//Add services to the container.
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
builder.Services.AddControllers();
//Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//builder.Services.AddSingleton<IAuthUserService, AuthUserService>();
//builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
builder.Services.AddHttpContextAccessor();
builder.Services.AddCors(options =>
{
options.AddPolicy("cors",
builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); });
});
//builder.Services.AddAuthorization(options =>
//{
// //By default, all incoming requests will be authorized according to the default policy.
// options.FallbackPolicy = options.DefaultPolicy;
//});
var app = builder.Build();
//Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
//app.UseAuthentication();
app.UseAuthorization();
app.UseCors("cors");
app.MapControllers();
app.Run();
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<aspNetCore processPath="dotnet" arguments=".\WindowsProxy.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
<validation validateIntegratedModeConfiguration="false" />
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
<!--ProjectGuid: d0c0a55a-a8fb-4ab1-b406-55db25ed63b0-->
I have tried multiple different configs, APP pool is defined using integrated 4.0 pipeline,
agent user does have full access to file directory. App pool identity is being used by agent account. I can get this to work just fine using swagger. Was having auth issues but seem to have resolved that. It looks like I am talking to the server correctly but the error indiciates a configuration issue.
When pinging from the browser directly I get:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
How do I find this API on the web?
We have a .net Core 3.1 MVC web application running with ServiceStack Ormlite 5.12. Currently we have a 'public' Open API for users who wish to access data programmatically. We use the following in our AppHost:
public class AppHost : AppHostBase
{
public AppHost(IServiceProvider services, IWebHostEnvironment env)
: base("My API", typeof(MyAPIService).Assembly)
{
_appServices = services;
_env = env;
}
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
...
HandlerFactoryPath = "/myapipath"
});
Plugins.Add(new OpenApiFeature
{
...
});
}
}
And in our Web.config:
<configuration>
<location path="myapipath">
<system.web>
<httpHandlers>
<add path="servicestack*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
<!-- Required for IIS7 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="servicestack*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
</location>
</configuration>
We have MyApp.ServiceModel and MyApp.ServiceInterface projects that are accessed from the https://{baseurl}/myapipath endpoint. This all works well so far.
We wish to keep the existing OpenAPI unchanged so that users don't need to change anything when updating to a new version. But we also want to add another API for use with an angular application, either by adding a separate endpoint for a 2nd API, or by filtering out what is visible in swagger with our existing API. Is it possible to add a 2nd API plugin with a different path that is separate from the existing API?
There can be only one ServiceStack Open API Plugin registered which lists all publicly accessible APIs within an AppHost.
If you want to visually differentiate APIs you can Group related APIs with Tags:
[Tag("angular")]
public class MyRequest { ... }
Alternatively you can choose to Exclude Services from Metadata Pages with:
[ExcludeMetadata]
public class MyRequestDto { ... }
would you help me?
i've created a web api on azure and chose not to allow anonymous requests but to use azure active directory to authenticate the requests. the app beneath has "sign-in and read user profile" permissions set.
if the controller behind the web api accepts GET requests it works, while it gives me the error : "You do not have permission to view this directory or page."
before i call the web api i open a iframe on the page (sharepoint page) to implicitly get the token from the web api, which calls the basic GET action below:
[ActionName("Connect")]
[HttpGet]
public IHttpActionResult Connect()
{
return base.Content(HttpStatusCode.OK, "OK", new JsonMediaTypeFormatter(), "text/plain");
}
later on i call via jquery another action (POST)...
public IHttpActionResult PostPromote([FromBody] string request)
but at this point i receive the 403 (Forbidden) message.
the CORS for my webapi is set in the web.config file:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://mytenant.sharepoint.com" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true"/>
</customHeaders>
</httpProtocol>
if i switch the method to GET it works, as well as (of course) if i permit anonymous requests.
thank you a lot, that's making me crazy.
I have had a look at this question:
Publish WebAPI and MVC projects to same Azure Web Site?
but it doesn not work properly for the "secondary" application.
and from that I learned about virtual directories in Azure web app services ( previously called Azure websites).
I am trying to deploy into the same Azure web apps 2 web applications. Both are ASP.NET 5 applications (they will be MVC 6) under a solution called MyOAuth:
MyApi: ASP.NET 5 application that should be accessible through myoauth.azurewebsites.com
MyAuth: ASP.NET 5 application that should be accessible through myoauth.azurewebsites.com/oauth
Solution 'MyOAuth'
|-src
|- MyApi
|- MyAuth
So in the Azure Web App service that I have created (called also MyOAuth), under settings I have the following Virtual Applications and Directories:
/ site\wwwroot Application
/oauth site\wwwroot\oauth Application
The Publish connection from Visual Studio 2015 for both of them are:
MyApi
Server: myoauth.scm.azurewebsites.net:443
Site Name: MyOAuth
User Name: *****
Password: ****
Destination URL: http://myoauth.azurewebsites.net
MyOAuth
Server: myoauth.scm.azurewebsites.net:443
Site Name: MyOAuth/oauth
User Name: *****
Password: ****
Destination URL: http://myoauth.azurewebsites.net/oauth
These are the Startup configuration for both projects:
Startup.cs for MyApi
//...
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello MyApi app");
});
}
Startup.cs for MyAuth
//...
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.Run(async (context) =>
{
await context.Response.WriteAsync("...And hello MyAuth app");
});
}
After publishing, when I access http://myoauth.azurewebsites.net I get the proper response Hello MyApi app, but when requesting http://myoauth.azurewebsites.net/oauth I get a server 500 error with text The page cannot be displayed because an internal server error has occurred.
I managed to retrieve the following DetailedError from the Azure LogFiles folder:
HTTP Error 500.19 - Internal Server Error The requested page cannot be
accessed because the related configuration data for the page is
invalid.
Detailed Error Information: Module IIS Web Core
Notification BeginRequest
Handler Not yet determined
Error Code 0x800700b7
Config Error Cannot add duplicate collection entry of type 'add'
with unique key attribute 'name' set to 'httpplatformhandler' Config
File \?\D:\home\site\wwwroot\oauth\web.config Requested URL
http://MyOAuth:80/oauth Physical Path D:\home\site\wwwroot\oauth
Logon Method Not yet determined Logon User Not yet determined
Config Source:
<handlers>
<add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
Could anybody advise on this or give me a solution on how to run 2 different ASP.NET 5 applications under the same Azure Web App Service, please?
Thank you!
Its possible following the folder structure outlined here:
https://github.com/aspnet/dnx/issues/928#issuecomment-171617386
THe problem is that I have yet not found tooling that makes it easy to do with vs2015 or VSTeamServices
One of the key things that I had to do to make it work (still did some manual deployments steps - but i found one issue in my setup that could help you also i think). The following will fix the 500.19 error
<handlers>
<remove name="httpplatformhandler" />
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
</handlers>
More information on same topic can be found at: Deploying aspnet5 apps to virtual directories on azure websites
I have deployed a Web API project to Azure Web app. And from a angularjs app I am trying a $http.get request to the API. but it gives a CORS(cross-origin) exception though I have enabled it in my Web API startup config
app.UseCors(CorsOptions.AllowAll);
I want to Enable CORS for Azure Web App, that would solve the problem I believe
EDIT
http://nearestbuyweb.azurewebsites.net/ this is the URL of the Web app. It is trying to access http://nearestbuyapi.azurewebsites.net/api/MenuBar where the exception occurs.
I think it is not possible with Azure Web App. MSDN Question
Please help!
Note: You use CORS settings to let other websites access your site's API. Not to access other site's APIs.
Based on your comments it sounds like you're getting the CORS error when you try to make external requests from your site. That's exactly the behavior CORS is supposed to block.
For the errors to go away you would have to apply the CORS config settings on the site who's API you're trying to access.
In your case you want to make sure you're applying the config changes on the http://nearestbuyapi.azurewebsites.net site. NOT on http://nearestbuyweb.azurewebsites.net/
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
I have CORS in Azure working using this:
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "PublicApi",
routeTemplate: "api/v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Web.config:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers></system.webServer>
You need to remove the options handler in IIS using web.config.
http://eugeneagafonov.com/post/38312919044/iis-options-cors-aspnet-webapi-en
Sorry Guys,
The issue happens only at my corporate network. Having googled I found that corporate network can be disable CORS requests . Found this here link