たとえば、次のようなAJAXリクエスト
function saveItem(imgurl) {
$.ajax(
{
url: '<%=Url.Action("SaveItem") %>' ,
dataType: "json" ,
data: {
categoryid: $( "#categoryid" ).val(),
itemid: null ,
name: $( "#name" ).val()
},
success: function (data) { $( "div[id^=edititem]" ).html( '' ).hide(); getItems($( "#categoryid" ).val()); },
error: function (e) { alert(e.responseText); }
}
)
}
* This source code was highlighted with Source Code Highlighter .
ブラウザの行から簡単に取得できるSaveItemメソッドを呼び出します。 これを防ぐには、この小さなActionFilterAttributeを使用します。
public class AjaxFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext. HttpContext .Request.IsAjaxRequest())
{
filterContext.Result = new RedirectToRouteResult( "Error" ,
new RouteValueDictionary(
new
{
controller = "Home" ,
action = "Error"
}));
}
}
}
* This source code was highlighted with Source Code Highlighter .
これで、ActionResultを返すメソッドはすべて[AjaxFilter]属性を設定する必要があり、それを直接呼び出したいユーザーは混乱します。 もちろん、View Error.aspxとそれに対応するメソッドをHomeコントローラー(またはリダイレクトする場所)で作成する必要があります