.NET CORE 屏蔽重复提交

加入session支持

public void ConfigureServices(IServiceCollection services)
{
    // add session support
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => false;
        options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
    });

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(100);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });

    // 没有下面这句,启动会失败,
    // 报这个错: InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore
    services.AddDistributedMemoryCache();
    // 因为PreventDoublePostAttribute用到了IAntiforgery,所以这里还要加
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
{
    ...
    app.UseStaticFiles();
    // add session pipepline
    app.UseSession();
    ...
}

 引入PreventDoublePostAttribute属性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class PreventDoublePostAttribute : ActionFilterAttribute
{
    private const string UniqFormuId = "LastProcessedToken";
    public override async void OnActionExecuting(ActionExecutingContext context)
    {
        IAntiforgery antiforgery = context.HttpContext.RequestServices.GetService(typeof(IAntiforgery)) as IAntiforgery;

        if (antiforgery == null)
            return;

        AntiforgeryTokenSet tokens = antiforgery.GetAndStoreTokens(context.HttpContext);

        if (!context.HttpContext.Request.Form.ContainsKey(tokens.FormFieldName))
        {
            return;
        }

        var currentFormId = context.HttpContext.Request.Form[tokens.FormFieldName].ToString();
        var lastToken = "" + context.HttpContext.Session.GetString(UniqFormuId);

        if (lastToken.Equals(currentFormId))
        {
            context.ModelState.AddModelError(string.Empty, "Looks like you accidentally submitted the same form twice.");
            return;
        }

        context.HttpContext.Session.Remove(UniqFormuId);
        context.HttpContext.Session.SetString(UniqFormuId, currentFormId);
        await context.HttpContext.Session.CommitAsync();
    }
}

使用

[HttpPost]
[PreventDoublePost]
public ActionResult<TodoItem> Create([FromForm] TodoItem item)
{
    AllItems.Add(item);
    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}

 测试

# test post 
POST https://localhost:44352/TodoItem/ HTTP/1.1
content-type: application/x-www-form-urlencoded
cache-control: no-cache

__RequestVerificationToken=form_id_1
&id=86336
&Summary=ttt
###

 PreventDoublePostAttribute属性只使用了tokens.FormFieldName,那么hardcode一个hidden formid应该也可以,这样就不需要AntiForgery了。
再说AntiForgery也不是这么用的。

### WMS系统的开发方法、技术和实现方式 #### 软件架构设计 WMS(Warehouse Management System)系统的设计通常采用分层架构模式,分为表示层、业务逻辑层和数据访问层。这种结构有助于模块化开发并提高可维护性和扩展性[^1]。 - **表示层**:负责用户界面展示以及交互操作处理。可以利用现代前端框架如React.js 或 Vue.js 构建响应式的Web应用程序。 - **业务逻辑层**:封装核心功能算法,例如库存分配策略、拣货路径优化等复杂计算过程。此部分可以用Java Spring Boot或者.NET Core来构建服务端API接口[^2]。 - **数据访问层**:连接后台数据库完成增删改查基本动作。推荐使用关系型数据库MySQL/PostgreSQL存储结构化信息;对于实时性强的需求场景,则考虑引入NoSQL解决方案MongoDB作为补充。 #### 关键技术选型 为了满足高效稳定运行的要求,在具体实施过程中还需要关注以下几个方面: - **并发控制机制** - 鉴于仓储环境中频繁发生的订单更新活动可能引发资源争用现象,因此有必要采取乐观锁或悲观锁手段保障事务一致性。 - **集成能力提升** - 借助标准化协议SOAP/RESTful Web Services与企业内部其他信息系统(比如ERP)无缝对接,简化跨平台协作流程的同时减少重复劳动量。 - **自动化设备支持** - 支持RFID读写器、条形码扫描枪等多种硬件终端接入,借助中间件程序屏蔽底层差异从而统一管理规范。 #### 示例代码片段 以下是基于Spring Boot框架创建的一个简单REST API用于接收来自客户端提交的新入库请求的例子: ```java @RestController @RequestMapping("/api/inventory") public class InventoryController { @Autowired private InventoryService inventoryService; @PostMapping("/receive") public ResponseEntity<String> receiveInventory(@RequestBody ReceiveRequest request){ try{ inventoryService.processReceive(request); return new ResponseEntity<>("Success", HttpStatus.OK); }catch(Exception e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值