我创建了一个 SQL 查询,通过检查查询字符串和 UserID 是否返回计数 1 来检查用户是否拥有数据库中的记录。这是下面的代码,它工作得非常好:
@{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var db = Database.Open("StayInFlorida");
var rPropertyId = Request.QueryString["PropertyID"];
var rOwnerId = WebSecurity.CurrentUserId;
var auth = "SELECT COUNT (*) FROM PropertyInfo WHERE PropertyID = @0 and OwnerID = @1";
var qauth = db.QueryValue (auth, rPropertyId, rOwnerId);
}
@if(qauth==0){
<div class="container">
<h1>You do not have permission to access this property</h1>
</div>
}
else {
SHOW CONTENT HERE
}
问题是我需要在至少 10 个不同的页面上应用此检查,也许将来会更多?我完全赞成使用可重用代码,但我不确定如何一次编写此代码,并在需要的每个页面上引用它。我已经尝试在中间嵌套布局页面的代码块中执行此操作,但我遇到了错误。关于什么是最好的方法有什么建议吗?还是我必须将其复制并粘贴到每个页面?
最佳答案
“Razor”方式是使用函数 (http://www.mikesdotnetting.com/Article/173/The-Difference-Between-@Helpers-and-@Functions-In-WebMatrix)。
将以下内容添加到 App_Code 文件夹中名为 Functions.cshtml 的文件中:
@functions {
public static bool IsUsersProperty(int propertyId, int ownerId)
{
var db = Database.Open("StayInFlorida");
var sql = @"SELECT COUNT (*) FROM PropertyInfo
WHERE PropertyID = @0 and OwnerID = @1";
var result = db.QueryValue (sql, propertyId, ownerId);
return result > 0;
}
}
然后在您的页面中:
@{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var propertyId = Request["PropertyID"].AsInt();
var ownerId = WebSecurity.CurrentUserId;
}
@if(!Functions.IsUsersProperty(propertyId, ownerId)){
<div class="container">
<h1>You do not have permission to access this property</h1>
</div>
}
else {
SHOW CONTENT HERE
}
关于layout - 在 Webmatrix 中添加可重用的代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20098654/