开发者

asp.net mvc jsonresult block external use

开发者 https://www.devze.com 2023-04-04 23:01 出处:网络
Is it possible to block any other use of json result and allow just requests from my application ? when we use something like this:

Is it possible to block any other use of json result and allow just requests from my application ? when we use something like this:

Json(q, JsonRequestBehavior.Allow开发者_如何学编程Get)

it allow all requests from anywhere.is there any authentication exist to check where request is from ?


I think you mean:

How to allow only AJAX requests?

If so, view the following blog post. It describes creating a reusable filter:

AjaxOnly attribute

The code seems quite simple, but I haven't used it myself:

public class AjaxOnlyAttribute : ActionFilterAttribute  
{  
    public override void OnActionExecuting(ActionExecutingContext filterContext)  
    {  
        if(!filterContext.HttpContext.Request.IsAjaxRequest())  
            filterContext.HttpContext.Response.Redirect("/error/404");  
    }  

    public override void OnActionExecuted(ActionExecutedContext filterContext)  
    {  

    }  
} 

That you can then apply to controllers and actions:

[AjaxOnly]  
public ActionResult AjaxActionMethod()  
{  
    //....  
}

The filter code presumes the existence of an action on some controller that can be reached by the following route:

/error/404

As a result, I have amended the code, and produced an easy way of adding an arbitrary error route (with a default value of "/error/404"):

public class AjaxOnlyAttribute : ActionFilterAttribute
{
    public AjaxOnlyAttribute(){}

    public AjaxOnlyAttribute(string ErrorRoute)
    {
        this.ErrorRoute = ErrorRoute;
    }

    string errorRoute = "/Error/404"; // default route
    public string ErrorRoute 
    {
        get { return errorRoute; }
        set { errorRoute = value; }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
            filterContext.HttpContext.Response.Redirect(this.ErrorRoute); //
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }
}

This can now be used as follows:

[AjaxOnly(ErrorRoute = "/MyArbitraryRoute/MyArbitraryParameter")
public ActionResult AjaxActionMethod()
{
   //....
}


Add the [Authorize] attribute to your methods or controllers that you want to protect. You can specify the group membership and a login will be required.


If you only want a method to be callable by your own application, change the method declaration from public to internal. This will limit the scope of the method to calls from within your application.

0

精彩评论

暂无评论...
验证码 换一张
取 消