在mvc 5中只允许在会话时间内进行一次操作

时间:2016-07-08 08:20:45

标签: c# asp.net-mvc

我有一个动作来计算帖子查看次数。但是在我的方法中,每次用户刷新页面时,它都会重新计算一次。我希望它表现为这个计数过程只发生一次会话中的不同帖子。有什么方法吗?

public ActionResult Index(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var model = new ViewModel()
        {
            // model operation
        };
        UpdatePostsViewCount((int)id);
        return View(model);
    }

//If the current user who is in the session has made it count for the same post before 
  it should not be counting again. When new session starts it can count as it's supposed to.

public void UpdatePostsViewCount(int postId)
    {                
        var toUpdate = _postService.GetPost(new IdInput { Id = postId });
        toUpdate.ViewCount += 1;
        _postService.UpdatePostsViewCount(toUpdate);            
    }

2 个答案:

答案 0 :(得分:0)

每次刷新名为方法索引的页面时,也称为方法export default class AssetsAdd extends React.Component { componentDidMount() { console.log(this) } handleSubmit(event) { if (this.refs.titleInput !== '') { event.preventDefault(); var asset = { date: '', title : this.refs.titleInput.value, id : '', type: this.refs.typeInput.value } return this.props.dispatch(addAsset(asset)) } } render() { return ( <div> <Row> <Portlet title='New Asset' form> <Form horizontal onSubmit={this.handleSubmit}> <FormGroup> <Label text='Title' size='3' /> <Input ref="titleInput" placeholder='Enter asset title' size='4'/> </FormGroup> <FormGroup> <Label text='Type' size='3' /> <Input ref="typeInput" placeholder='Enter asset type' size='4'/> </FormGroup> <FormGroup> <Label text='Description' size='3' /> <Input ref="descriptionInput" placeholder='Enter asset description' size='4'/> </FormGroup> <FormGroup> <Label text='Documentation' size='3' /> <Input ref="documentationInput" placeholder='Enter documentation URL' size='4'/> </FormGroup> <FormActionBar> <SubmitButton value='Submit'/> <CancelButton value='Cancel'/> </FormActionBar> </Form> </Portlet> </Row> </div> ) } } function mapStateToProps(state) { return { assets: state.assets }; } export const AssetAddContainer = connect(mapStateToProps)(AssetsAdd); 并递增UpdatePostsViewCount

要避免这种情况,您需要获取客户端显示的帖子。并检查 - 是否有任何新帖子。只有在计算之后才会发布并更新它们。

P.S。:通过JS在客户端更好的方式。

答案 1 :(得分:0)

一个想法可能是存储用户访问过的每个帖子的ID,并检查每个请求是否是用户已经访问过的页面。

如果您想避免在每次请求时对数据库执行请求,您可以将信息存储在数据库中并对其进行缓存。如果您的缓存对该用户来说是空的,那么您可以执行您的请求。