c# - Handling CORS Preflight in Asp.net Web API -
i have 3 applications in architecture.
on same server having different port numbers.
a - token application (port 4444) - asp.net webapi b - api application (port 3333) - asp.net webapi c - ui application (port 2222) - angularjs app. the application flow below
1- ui project gets token token application (it requires windows auth.) ex : awxrsdsaweffs12da
2- ui application puts token custom header named "accesstoken"
ex : accesstoken : awxrsdsaweffs12da
3- ui application sends request api application ex: http:myaddress:3333/api/therestservicehere
ui application gets 401 error. sends options method. (i guess preflight issue)
in web api project enabled cors below.
public static void register(httpconfiguration config) { .... //cors var cors = new enablecorsattribute("*", "*", "*"); config.enablecors(cors); .... } config
public static class webapiconfig { public static void register(httpconfiguration config) { //cors var cors = new enablecorsattribute("*", "*", "*"); config.enablecors(); // web api routes config.maphttpattributeroutes(); config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional } ); var json = config.formatters.jsonformatter; json.serializersettings.preservereferenceshandling = preservereferenceshandling.none; //object olursa $id gelecek json objeleri başına json.serializersettings.referenceloophandling = referenceloophandling.ignore; json.serializersettings.formatting = formatting.none; json.serializersettings.contractresolver = new camelcasepropertynamescontractresolver(); config.formatters.remove(config.formatters.xmlformatter); } } so looking solution call api application (b) controllers , 200 :)
regards
i fixed in application working on creating module responds requests using options verb. should modify bit include verbs , content type application requesting. in case, decided post json (which requires pre-flight check). module follows:
public class optionsmodule : ihttpmodule { public void init(httpapplication context) { context.beginrequest += (sender, args) => { var app = (httpapplication) sender; if (app.request.httpmethod == "options") { app.response.statuscode = 200; app.response.addheader("access-control-allow-headers", "content-type"); app.response.addheader("access-control-allow-origin", apisettings.applicationorigin); app.response.addheader("access-control-allow-credentials", "true"); app.response.addheader("access-control-allow-methods", "post,get,options"); app.response.addheader("content-type", "application/json"); app.response.end(); } }; } public void dispose() { } } then need register in web.config:
<system.webserver> <modules> <add name="handleoptions" type="namespace.optionsmodule" /> </modules> </system.webserver> another thing may want specify allowed origin explicitly. chrome doesn't having wildcard there.
Comments
Post a Comment