c# - MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource -
i tried written in article: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api, nothing works. i'm trying data webapi2 (mvc5) use in domain using angularjs.
my controller looks this:
namespace tapuzwebapi.controllers { [enablecors(origins: "http://local.tapuz.co.il", headers: "*", methods: "*", supportscredentials = true)] [routeprefix("api/homepage")] public class homepagecontroller : apicontroller { [httpget] [route("getmainitems")] //[responsetype(typeof(product))] public list<usp_mobileselecttopsecondaryitemsbycategoryresult> getmainitems() { homepagedalcs dal = new homepagedalcs(); //three product added display data //homepagepromoteditems.value.add(new homepagepromoteditem.value.firstordefault((p) => p.id == id)); list<usp_mobileselecttopsecondaryitemsbycategoryresult> items = dal.mobileselecttopsecondaryitemsbycategory(3, 5); return items; } } }
you need enable cors in web api. easier , preferred way enable cors globally add following web.config
<system.webserver> <httpprotocol> <customheaders> <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>
please note methods individually specified, instead of using *
. because there bug occurring when using *
.
you can enable cors code.
update
following nuget package required: microsoft.aspnet.webapi.cors
.
public static class webapiconfig { public static void register(httpconfiguration config) { config.enablecors(); // ... } }
then can use [enablecors]
attribute on actions or controllers this
[enablecors(origins: "http://www.example.com", headers: "*", methods: "*")]
or can register globally
public static class webapiconfig { public static void register(httpconfiguration config) { var cors = new enablecorsattribute("http://www.example.com", "*", "*"); config.enablecors(cors); // ... } }
you need handle preflight options
requests http options
requests.
web api
needs respond options
request in order confirm indeed configured support cors
.
to handle this, need send empty response back. can inside actions, or can globally this:
# global.asax.cs protected void application_beginrequest() { if (request.headers.allkeys.contains("origin") && request.httpmethod == "options") { response.flush(); } }
this check added ensure old apis
designed accept get
, post
requests not exploited. imagine sending delete
request api
designed when verb didn't exist. outcome unpredictable , results might dangerous.
Comments
Post a Comment