在我的 ASP .NET MVC 3 Web 应用程序中,我使用了很多局部 View 。在某些情况下,我通过正常的渲染调用使用这些局部 View
<div id="attributes">
@Html.Partial("_DeviceAttributesPartial", Model.DeviceAttributes)
</div>
在其他情况下使用 AJAX:
$.ajax({
url: '@Url.Action("GetDeviceAttributes")',
type: 'POST',
data: { deviceID: device, deviceTypeID: devicetype, deviceModelID: devicemodel },
success: function (result) {
// when the AJAX succeeds refresh the device model drop down holder
$('#attributes').html(result);
}
});
我试图找到一种方法来阻止用户直接转到我的部分 View ActionResults,例如这个:
public ActionResult GetDeviceModelList(int deviceTypeID)
{
var model = new EditDeviceViewModel();
var deviceType = _db.DeviceTypes.Single(t => t.ID == deviceTypeID);
model.DeviceModelList = new SelectList(_db.DeviceModels.Where(m => m.DeviceType.ID == deviceType.ID), "ID", "Model");
return PartialView("_DeviceModelListPartial", model);
}
我偶然发现了 this answer只需将操作设置为 private
。我试了一下,它似乎有效,但我对这样做感到不安,不知道会发生什么其他副作用。
所以我的问题是:
- 将操作设置为
private
是否明智? - 这样做可能会产生什么其他副作用?
- 只有通过
POST
才能执行的操作怎么样?
注意:大部分部分操作结果函数都是[HttpPost]
,所以我不相信它们无论如何都可以访问。
最佳答案
降低 Action 的可见性将阻止该 Action 在 Controller 之外可用。每个人都可以使用 [HttpPost] 属性修饰的操作,但只能通过 POST http 请求,这有点超出普通用户的能力。
考虑用 [ ChildActionOnly 装饰 Action ] 您不会通过 POST 访问的属性,而是使用 [HttpPost] 修饰这些操作。
关于c# - 将 ActionResult 函数声明为私有(private)函数以防止直接访问 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7397397/