i have web api 2
backend hosted on azure , angularjs
forntend. understand of http request
use pre-check options request
. question how implement backend way, options requests
return 200 if there action in controller handle following get/post/put/delete/...
.
non elegant way solve task adding in each controller manually
[acceptverbs("options")] public httpresponsemessage options() { var resp = new httpresponsemessage(httpstatuscode.ok); resp.headers.add("access-control-allow-origin", "*"); resp.headers.add("access-control-allow-methods", "get,delete"); return resp; }
or override messagehandlers
public class optionshttpmessagehandler : delegatinghandler { protected override task<httpresponsemessage> sendasync( httprequestmessage request, cancellationtoken cancellationtoken) { if (request.method == httpmethod.options) { var apiexplorer = globalconfiguration.configuration.services.getapiexplorer(); var controllerrequested = request.getroutedata().values["controller"] string; var supportedmethods = apiexplorer.apidescriptions.where(d => { var controller = d.actiondescriptor.controllerdescriptor.controllername; return string.equals( controller, controllerrequested, stringcomparison.ordinalignorecase); }) .select(d => d.httpmethod.method) .distinct(); if (!supportedmethods.any()) return task.factory.startnew( () => request.createresponse(httpstatuscode.notfound)); return task.factory.startnew(() => { var resp = new httpresponsemessage(httpstatuscode.ok); resp.headers.add("access-control-allow-origin", "*"); resp.headers.add( "access-control-allow-methods", string.join(",", supportedmethods)); return resp; }); } return base.sendasync(request, cancellationtoken); } }
and in config
globalconfiguration.configuration.messagehandlers.add(new optionshttpmessagehandler());
even second option not perfect though... no native build in support
Comments
Post a Comment