How to develop a custom action filter for checking request is coming from same domain

StackOverflow https://stackoverflow.com/questions/19955095

  •  30-07-2022
  •  | 
  •  

سؤال

i am new in MVC but i want to develop a custom attribute which will be custom action filter and which can used at controller or action method level. it will check that request is coming from same domain or different domain. if different domain then unauthorized error will be sent to caller.

attribute look like

[IsRequestFromSameDomain]
public class HomeController : Controller {
  public ActionResult Index() {


  }
}

i want to send error code & error message from where caller can understand that he has no access to any controller or action method from different domain.

another most important thing is attribute can be used for whole controller or can be used for any action method. so guide me how could i do it. thanks

هل كانت مفيدة؟

المحلول

public class IsRequestFromSameDomainAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
        {
            //The HOST is not the same, so you need to redirect to an error view or something like that
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top