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.
Related
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!
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.
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
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.
I have a web api method:
[HttpPost, ActionName("GET")]
public string Get(string apiKey, DateTime start, DateTime end)
{
var user = db.Users.SingleOrDefault(u => u.Id == apiKey);
if (user == null)
{
return string.Empty;
}
var records = db.Histories.Where(h => h.Date >= start && h.Date <= end);
return JsonConvert.SerializeObject(records);
}
And here is the url I tried to call the method, but it doesn't reach to the method.
http://localhost:11847/api/History/Get?apiKey=398cfa9b-8c5c-4cf4-b4f3-8904a827ff22&start=2014-01-01&end=2014-12-01
I also have changed the WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
from "api/{controller}/{id} to "api/{controller}/{action}
UPDATE 2022:
It's 2022 now. A lot has changed. There are plenty of clients out there. I will list my favourites.
Postman - Postman has improved since I answered this in 2014. Apart from being a client, it has other features like collaboration, scripting, importing endpoints from various sources like Open API etc. Pretty simple to use.
Thunder Client - A Visual Studio extension that has a similar feel as Postman but a pure API client.
For testing the api, you can use fiddler(http://www.telerik.com/fiddler) or a chrome app called postman.
You should also try the POSTMAN by http://www.getpostman.com/ which can be added to chrome as an app. It really good and lets you organize your apis.
I found out how to write the url in Fiddler:
In the Composer panel:
Parsed:
GET : http://localhost:11847/api/History/GetRecords?apiKey=398cfa9b-8c5c-4cf4-b4f3-8904a827ff22&start=2014-01-01&end=2014-12-01
Request Headers:
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:11847
Content-Length: 0