web api routes not working with CORS enabled. - asp.net-web-api

I have CORS enabled in my web api application. and i have API controllers with both classic REST Function names like Get() and Get(string id) and a controllers with custom function names e.g.
[HttpGet]
GetSomeThing()
i have routes configured like this
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
with this arrangement i get an error No 'Access-Control-Allow-Origin' header is present when i try to call controller with Classic REST functions.
e.g. /api/Controller
and if i take route with action after route without action , it gives me the same error on controller calls with custom function names.
e.g. /api/Controller/Function
please note that i have
[EnableCorsAttribute("http://localhost:xxxx", "*", "*")]
attribute on both controllers. and these calls are being made from angular application.
kindly advice.

Had the same issue. Fixed it by adding CORS headers directly to web.config. No other changes are needed.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-type, accept, SOAPAction, origin" />
</customHeaders>
</httpProtocol>
</system.webServer>
Additionally, if you installed CORS via NuGet and were using a previous version of WebAPI, then you may need to uninstall it. CORS will update certain core WebAPI assemblies that may cause compatibility issues, i.e., routes not working.
And of course, you will probably want to limit the allowed origins by replacing the "*" in the Access-Control-Allow-Origin value with the URL's you want to allow.

I ran into this issue and I found it a nightmare to get cors to work.
The fix for me in the end was to remove all references to cors in my app and add just one line in the WebAPIConfig
public static void Register(HttpConfiguration config)
{
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE, TOKEN"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "rest/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
I also removed the custom headers from my web.config. Hope this help anyone else facing cors issues.

Related

No custom/authorization Headers in MVC 5 controller

I have an MVC 5 ViewController which does not accept headers from an Ajax call. The ajax call origin is a different website then the controller.
The Ajax call looks like:
window.jQuery.ajax({
url: 'http://localhost:54155/TestView',
headers: {'Authorization': 'token'},
cache: false,
contentType: 'application/json; charset=utf-8',
method: 'Get',
dataType: 'json',
data: {}
}).success(alert('succes?'))
.error(alert('failed'))
});
Cors is enabled on the controller side:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
And I'm trying to reach this controller:
public class TestViewController : Controller
{
public ActionResult Index()
{
var keys = Request.Headers.AllKeys;
return View();
}
}
If I send the request to a WebApi based on a WEP API 2 controller, the headers are ok. If I send a request with postman to the mvc controller the headers are ok as well.
The Headers contain the header Access-Control-Request-Headers, which has the value authorization. But Request.Headers["Authorization"] is null.
Custom headers like X-MyHeader turn up as value from Access-Control-Request-Headers, but when used like a key, they are all null.
Which part am I missing?
I had a same kind of issue - but this might resolve your problem
Install Microsoft.AspNet.WebApi.Cors from NuGet - Run this command
(Install-Package Microsoft.AspNet.WebApi.Cors) in your package
manager console - this will install your Cors
Remove your access allow origin code from your Web.config file
If it is Web Api add the below cod in your WebApiConfig.cs if not try to add in your Gloabl.asax
var cors = new EnableCorsAttribute("*", "*", "*", "*");
config.EnableCors(cors);
You will be wondering where that method EnableCors() will come using System.Web.Http.Cors; add this line in your using and see the magic
This might solve your problem - Finally its not a good idea to access your MVC controller from different domain try you use WebApi
If you want to access your MVC controller try out your ajax code form the same domain
Because WebApi is stateless but MVC is kind of session - Thanks happy coding !!

Web API 2.0 Routing not working properly when deployed to godaddy

I am getting very strange routing behaviour issue in Asp.net Web API 2.0. When I am running my API in localhost it works fine with URL api/{controller} but now I have deployed this web API to GoDaddy shared server at that time it is working with api/api/{controller}. It is working when I use "api" keyword two times. If I use api/{controller} it gives me
404 error.(resource not found).
Can someone please help me to identify this strange behaviour?
In webapi.config.cs file default route is register.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
and On Every controller I have used RoutePrefix as below
[RoutePrefix("api/test")]
public class Testontroller : ApiController
{
}
Thanks In Advance!

Cors not working in web api 2.0

I'm trying very hard to understand and enable CORS in a web api project. I've hit a blocking point. I've started with an ASP.NET MVC Web Api 2 project with an ASP.NET identity. Whatever I do seems to not work.
I've deleted my global.asx file and my startup looks like this:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration configuration = new HttpConfiguration();
// I'm not sure it this is the proper way to use webapiconfig
WebApiConfig.Register(configuration);
app.UseWebApi(configuration);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
}
}
and the WebApiConfig.Register code is:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.AddODataQueryFilter();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
RegisterModels(); //Automapper here
}
I have the mc aspnet cors and microsoft owin host System web installed.
The "[assembly: OwinStartup(typeof(MyProject.Startup))]" is in place, and in the web.config I have:
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
</appSettings>
I only call app.UseCors(CorsOptions.AllowAll) to enable CORS, no other way like config.enableCors or anything else, but whenever I try getting the token or anything in the API, I get the error:
Reason: CORS header ‘Access-Control-Allow-Origin’ missing.
I have tried putting a breakpoint in the Configuration method but it is not called... ever. I'm debugging with IIS Express.
Nothing worked for me.. after many tries I finally managed to get something working.
if you have the same problem..
1) remove anything related to cors from the nugget packages installed .. everything.
2) remove anything related to cors from the web.config.
3) In Gloabal.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var response = context.Response;
response.AddHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("X-Frame-Options", "ALLOW-FROM *");
if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PATCH, PUT");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.AddHeader("Access-Control-Max-Age", "1000000");
response.End();
}
}
This work for both /api and /token.
This is a generic solution please be aware before deploying it to prod.
Hope will help anyone who has the same problem.

CORS issue on chrome & firefox

The web API from IIS 7.5 are not responding for Chrome & Firefox.
I am getting the following error in chrome
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.xx.xx.xx:81' is therefore not allowed access
Firefox throw 401 unauthorized error.
Works perfectly on IE 11
Are there any additional setting required for these browsers?
First install WebApi Cors NuGet Package:
Install-Package Microsoft.AspNet.WebApi.Cors
Then in your WebApiConfig.cs file:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//other code
}
}
This way you enable CORS header globally allowing cross-site requests from any domain. If you want to allow cross-site requests from only a single (or a list of) domain, then change the constructor parameters of EnableCorsAttribute:
new EnableCorsAttribute("http://alloweddomain.com", "*", "*");
You may also apply the EnableCorsAttribute on a Controller or Action basis.
More information on the official documentation: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
"A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves"
You can use a chrome addon to allow CORS:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

web api default action selector

I have web api 1 in my project. I can't use web api 2. This is my route config
config.Routes.MapHttpRoute(
name: "images api",
routeTemplate: "api/objects/{objectId}/{controller}/{action}",
defaults: new { controller = "Images" });
I would like that post request hit post action of my ImagesController (action is named Post), and that get request hit method named Get. In both cases I get 404. What I'm missing?
This is solution:
config.Routes.MapHttpRoute(
name: "images api",
routeTemplate: "api/objects/{objectId}/{controller}",
defaults: new { controller = "Images" });
Just excluded action from routetemplate.

Resources