c# - Web API v2 Filter checking different types for same field -
i have code below in api filter. samplerequester object information form. has property called captcha. works great have other forms have captcha property. , work samplerequester objects. how check object captcha property?
public class validatecaptcha : actionfilterattribute { public override void onactionexecuting(httpactioncontext actioncontext) { var cookiepayload = actioncontext.request.getcookie("mycaptcha"); samplerequester requester = (samplerequester)actioncontext.actionarguments["requester"]; if(cookiepayload !== requester.captcha) { actioncontext.response = actioncontext.request.createresponse(httpstatuscode.forbidden); } } }
if know possible types in advance, can use as operator:
public class validatecaptcha : actionfilterattribute { public override void onactionexecuting(httpactioncontext actioncontext) { var cookiepayload = actioncontext.request.getcookie("mycaptcha"); var requester = actioncontext.actionarguments["requester"] samplerequester; if (requester != null && cookiepayload == requester.captcha) return; requester = actioncontext.actionarguments["requester"] anotherrequester; if (requester != null && cookiepayload == requester.captcha) return; actioncontext.response = actioncontext.request.createresponse(httpstatuscode.forbidden); } } if don't, expect whatever type have property captcha, can use dynamic:
public class validatecaptcha : actionfilterattribute { public override void onactionexecuting(httpactioncontext actioncontext) { var cookiepayload = actioncontext.request.getcookie("mycaptcha"); dynamic requester = actioncontext.actionarguments["requester"]; if (requester != null && cookiepayload == requester.captcha) return; actioncontext.response = actioncontext.request.createresponse(httpstatuscode.forbidden); } } ideally, first option, while making sure requesters implement same interface, can use as interface type.
i wonder, why have captcha value in cookie?
Comments
Post a Comment