【问题标题】:Error AntiForgeryToken C# MVC错误 AntiForgeryToken C# MVC
【发布时间】:2017-06-26 17:15:23
【问题描述】:

我正在研究我的项目,它是一个使用 MVC 和 EntitieFrameworks、C# 和 Visual Studio 的项目。 我使用通过 sql server 2016 获得的模型中的实体创建控制器和视图。为此,一切正常。 我的 cshtml 中的 AntiForgeryToken 属性存在问题,导致此错误。

 claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' was not present on the provided ClaimsIdentity.

System.InvalidOperationException: A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' was not present on the provided ClaimsIdentity.

那么,为什么要追加?这是框架自动生成的代码,我不知道为什么会出现这个错误。你能帮我吗? 我的cshtml以

开头
@model Entities.Producto

@{ViewBag.Title = "Crear Producto";}

<h2>Nuevo producto</h2>


@using (Html.BeginForm()) 
{
       @Html.AntiForgeryToken()

还有我的控制器

 namespace Web.Controllers
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Entities;
using Services;
using Web.Models;


public class ProductoController : BaseController
{
    IProductoService productoService;
    IRubroService rubroService;
    IProveedorService proveedorService;

    public ProductoController(IProductoService productoService, IRubroService rubroService, IProveedorService proveedorService)
    {
        this.productoService = productoService;
        this.rubroService = rubroService;
        this.proveedorService = proveedorService;
    }
    // GET: Producto
    public ActionResult Index()
    {
        List<Producto> productos = this.productoService.ObtenerProductos();

        List<Producto> productosVM = new List<Producto>();
        foreach (Producto producto in productos)//.Where(x => x.Activo == true))
        {
            if (producto.IdRubro != null)
            {
                producto.Rubro = this.rubroService.ObtenerRubro(producto.IdRubro.Value);
            }
            if (producto.IdProveedor != null)
            {
                producto.Proveedor = this.proveedorService.ObtenerProveedor(producto.IdProveedor.Value);
            }
            productosVM.Add(producto);
        }
        return View(productosVM);
    }

    // GET: Producto/Details/5
    public ActionResult Details(int? id)
    {
        Producto producto = this.productoService.ObtenerProducto(id.Value);
        if (producto == null)
            return HttpNotFound();


        return View(producto);
    }

    // GET: Producto/Create
    public ActionResult Create()
    {
        ViewBag.TiposRubro = new SelectList(this.rubroService.ObtenerRubros(), "Id", "Nombre");
        ViewBag.TiposProveedor = new SelectList(this.rubroService.ObtenerRubros(), "Id", "Nombre");
        return View();
    }

    // POST: Producto/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Descripcion,Codigo,Cantidad,Costo,Precio,Fecha,IdRubro,IdProveedor,StockMinimo,Activo,StockMaximo")] Producto producto)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if (this.productoService.ObtenerProducto(producto.Id) == null)
                {
                    producto.FechaModificacion = DateTime.Today;
                    this.productoService.Crear(producto);
                    this.Success("Producto creado correctamente.");
                    return RedirectToAction("Index");
                }
                else
                {
                    this.Information("El producto ya existe.");
                }
            }
        }
        catch (Exception ex)
        {
            ViewBag.IdProveedor = new SelectList(this.proveedorService.ObtenerProveedores(), "Id", "Nombre", producto.IdProveedor);
            ViewBag.IdRubro = new SelectList(this.rubroService.ObtenerRubros(), "Id", "Nombre", producto.IdRubro);
            this.Error("Hubo un error al crear el producto");
            return View(producto);
        }

        ViewBag.IdProveedor = new SelectList(this.proveedorService.ObtenerProveedores(), "Id", "Nombre", producto.IdProveedor);
        ViewBag.IdRubro = new SelectList(this.rubroService.ObtenerRubros(), "Id", "Nombre", producto.IdRubro);
        return View(producto);
    }

    // GET: Producto/Edit/5
    public ActionResult Edit(int id)
    {
        Producto producto = this.productoService.ObtenerProducto(id);

        if (producto == null)
        {
            return HttpNotFound();
        }

        ViewBag.IdProveedor = new SelectList(this.proveedorService.ObtenerProveedores(), "Id", "Nombre", producto.IdProveedor);
        ViewBag.IdRubro = new SelectList(this.rubroService.ObtenerRubros(), "Id", "Nombre", producto.IdRubro);
        return View(producto);
    }

    // POST: Producto/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Producto producto)
    {
        try
        {
            if (ModelState.IsValid)
            {
                producto.FechaModificacion = DateTime.Now;
                this.productoService.Actualizar(producto);
                //this.Success("Producto actualizado con exito");
                return RedirectToAction("Index");
            }

            ViewBag.IdProveedor = new SelectList(this.proveedorService.ObtenerProveedores(), "Id", "Nombre", producto.IdProveedor);
            ViewBag.IdRubro = new SelectList(this.rubroService.ObtenerRubros(), "Id", "Nombre", producto.IdRubro);
            this.productoService.Actualizar(producto);
            this.Error(ModelState.Values.First().Value.Culture.Calendar.AlgorithmType.ToString());
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ViewBag.IdProveedor = new SelectList(this.proveedorService.ObtenerProveedores(), "Id", "Nombre", producto.IdProveedor);
            ViewBag.IdRubro = new SelectList(this.rubroService.ObtenerRubros(), "Id", "Nombre", producto.IdRubro);
            this.Error("Hubo un error al actualizar el producto");
            return RedirectToAction("Index");
        }
    }

    // GET: Producto/Delete/5
    public ActionResult Delete(int? id)
    {
        Producto producto = this.productoService.ObtenerProducto(id.Value);

        if (producto == null)
        {
            return HttpNotFound();
        }
        return View(producto);
    }

    // POST: Producto/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        this.productoService.Borrar(id);
        return RedirectToAction("Index");
    }
}

}

谢谢!!

【问题讨论】:

  • 请包含一些处理表单回发的控制器代码。
  • 当我尝试创建产品时完成@parameter其附加
  • 哪个动作引发了错误?通常 AntiForgeryToken 位于 POST(您的 BeginForm)上,但我在您的控制器中看不到 POST 方法。
  • 您使用哪种身份验证?我看到了 BaseController 的自定义实现。请参阅thisthis 了解可能的解决方案。
  • 如果你添加到你的 Global.asax.cs 会发生什么:AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;?

标签: c# asp.net-mvc asp.net-mvc-5


【解决方案1】:

使用以下代码检查并更新您的 Global.asax.cs 文件,您需要添加 AntiForgeryConfig

命名空间 [您的项目名称] { 公共类 MvcApplication : System.Web.HttpApplication { 受保护的无效 Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; } } }

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 2010-11-23
    • 2011-10-09
    • 2013-07-22
    相关资源
    最近更新 更多