我有一个MVC项目。其中我有一个核心域模型,代表我系统中的实体。我有一个Car对象和Image对象。汽车有图像。我还有汽车库和汽车服务类。我正在尝试提供从UI中删除汽车数据的功能。所以我创建了一个名为DeleteCar的SP。这个sp将由汽车存储库类调用。但汽车删除是基于用户角色。如果用户是管理员,那么他可以删除它,但如果他不是,他将不被允许这样做。因此,如果在此示例中允许或不允许用户,我决定使用我的SP:
ALTER PROCEDURE [dbo].[DeleteCar]
(
@CarId INT
,@UserId INT
)
AS
BEGIN
DECLARE @ImagesNamesToBeDeleted Table([FIleName] NVARCHAR(255))
DECLARE @IsAuthorized bit = 0;
SELECT @IsAuthorized = dbo.IsAuthorizedToDeleteCar(@CarId, @UserId);
IF(@IsAuthorized = 0)
BEGIN
IF EXISTS(SELECT 1 FROM @ImagesNamesToBeDeleted)
BEGIN
SELECT @IsAuthorized AS IsAuthorized , [FIleName] AS FIleName FROM @ImagesNamesToBeDeleted
END
ELSE
BEGIN
SELECT @IsAuthorized AS IsAuthorized , '' AS FIleName
END
END
SET NOCOUNT ON;
DECLARE @TranCount INT;
SET @TranCount = @@TRANCOUNT;
BEGIN TRY
IF @TranCount = 0
BEGIN TRANSACTION
ELSE
SAVE TRANSACTION DeleteCar;
IF (@IsAuthorized = 1)
BEGIN
-- Delete car data
IF EXISTS(SELECT 1 FROM @ImagesNamesToBeDeleted)
BEGIN
SELECT @IsAuthorized AS IsAuthorized , [FIleName] AS FIleName FROM @ImagesNamesToBeDeleted
END
ELSE
BEGIN
SELECT @IsAuthorized AS IsAuthorized , '' AS FIleName
END
END
LBEXIT:
IF @TranCount = 0
COMMIT;
END TRY
BEGIN CATCH
DECLARE @Error INT, @Message VARCHAR(4000), @XState INT;
SELECT @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE();
IF @XState = -1
ROLLBACK;
IF @XState = 1 AND @TranCount = 0
rollback
IF @XState = 1 AND @TranCount > 0
ROLLBACK TRANSACTION DeleteCar;
RAISERROR (' DeleteCar: %d: %s', 16, 1, @error, @message) ;
END CATCH
END
Sp很好。但我正在撤回图像名称,以便我可以从我的服务器中物理删除这些图像。
如果用户被授权,如此可用的返回结果
IsAuthorized FileName
1 A.jpg
如果用户不是
IsAuthorized FileName
0 - 无数据
这是调用SP
的repoisptry方法public async Task<IList<Image>> DeleteCarAsync(int carId, int userId)
{
var parameters = new[]
{
new SqlParameter("CarId", SqlDbType.Int) {Value = carId},
new SqlParameter("@UserId", SqlDbType.VarChar) {Value = userId}
};
using (var reader = await SqlHelper.ExecuteReaderAsync(_connectionString, CommandType.StoredProcedure, "DeleteCar", parameters))
{
return reader.Select(r =>
{
var image = new Image
{
FileName = r["FileName"].ToString(),
IsAuthorized -- I want to read this value becuase based on it i Will decide if I will physically delete the images or not.
};
return image;
}).ToList();
}
}
阅读IsAuthorized的最佳方式是什么?
我应该在我的图像模型IsAuthorized中添加一个bool属性,就像我现在正在做什么一样?
然后我会这样做
if (images[0].IsAuthorized)
{
// delete images physically
}
还有其他方式吗?
答案 0 :(得分:0)
是的,这种方式可行。更好的用户体验是甚至不允许用户尝试删除他们无权删除的汽车。这样客户就不必看到错误消息。首次构建页面时,您可以在模型上发送IsAuthorized
标志,并相应地更改页面。
如果用户的权限在呈现时间页和删除时间之间发生了变化,您可能仍希望在删除时进行IsAuthorized
检查。