The same origin policy enforced in browsers as a defense against cross-site request forgery (CSRF) attacks has traditionally prevented a browser from calling an API method deployed in a separate domain or server from which the web application originated and is hosted.
But there are scenarios where you want your API to be accessible across domains - say internally across applications or if you are serving your Web API as a public API.
Before the advent of CORS (Cross Origin Resource Sharing), developers worked around this using JSONP (P for padding which implies the returned JSON needs to be parsed before deserializing it). JSONP makes use of calling the Web API over an http endpoint using a src attribute inside a <script> tag as <script> tags are allowed cross domain.
But JSONP is more like a hack and now modern browsers support CORS. To Enable CORS is very easy. Download the Nuget package for CORS and in your configuration setup in WebApiConfig.cs, make an entry as
config.EnableCORS();
And then as an example, just mark your controller class or GET action methods in your Web API with
[EnableCorsAttribute("http://localhost:52347", "*", "GET")]
The three parameters can be a list of comma separated values or * (for all). The first parameter is for the list of valid origins (the origin of the client apps that will be accessing the API), the second for the list of allowed headers and the third for a list of allowed HTTP methods.
Trivia:
1) IE will not treat a different port where your Web Service is deployed as a different domain in your local environment. But when it is deployed in separate servers, then it will enforce the same origin policy.
2) Use JsonFormatter's ContractResolver in the WebApiConfig.cs file to keep your C# property names as PascalCase and JSON properties as CamelCase so you don't have to compromise on best practices on either end.
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
No comments:
Post a Comment