0

Im working on my tesis that its a project using MVC and EntitieFrameworks, C# and Visual Studio. I create my controllers and views using my entities from the model that i get through sql server 2016. For that, its all ok. I have a problem with AntiForgeryToken property in my cshtml that trow this error.

 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.

So, why this append? This is autogenerated code from framework and i dont know why is this error. Can u help me? My cshtml starts with

@model Entities.Producto

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

<h2>Nuevo producto</h2>


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

And my Controller

 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");
    }
}

}

Thanks!!

  • Please include some of your controller code that handles the postback from the form. – parameter Jun 26 '17 at 17:20
  • Done @parameter its append when im try to create a Product – MarianoVeloso Jun 26 '17 at 17:23
  • Which action is throwing the error? Usually the AntiForgeryToken is on the POST (your BeginForm), but I don't see a POST method in your controller. – C. Helling Jun 26 '17 at 17:50
  • What kind of authentication are you using? I see a custom implementation for a `BaseController`. See [this](https://stackoverflow.com/questions/30976980/mvc-5-owin-login-with-claims-and-antiforgerytoken-do-i-miss-a-claimsidentity-pr) and [this](https://stackoverflow.com/questions/19977833/anti-forgery-token-issue-mvc-5) for possible solutions. – Jasen Jun 26 '17 at 17:52
  • now adding the complete controller @C.Helling. Like you said, i have this error on my POST create. – MarianoVeloso Jun 26 '17 at 18:16
  • Im not using any kind of authentication, for now i didnt implement users @Jasen – MarianoVeloso Jun 26 '17 at 18:19
  • 1
    What happens if you add to your Global.asax.cs: `AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;`? – C. Helling Jun 26 '17 at 18:20
  • I already have that in my Global.asax.cs @C.Helling. Thats the most common resolution for this problem in others post here, but for me doesnt work – MarianoVeloso Jun 26 '17 at 18:25
  • Well then in that case, what purpose does your AntiForgeryToken serve? It seems that you have Claims-based authentication, but that it is not setup properly. I'd consider removing it, or taking a look here: https://stackoverflow.com/questions/19977833/anti-forgery-token-issue-mvc-5 – C. Helling Jun 26 '17 at 18:28
  • I will keep in mind that in future to adding users... i think the best option right now its like you said, removing @Html.AntiForgeryToken() ... – MarianoVeloso Jun 26 '17 at 18:33
  • Check this out: https://stack247.wordpress.com/2013/02/22/antiforgerytoken-a-claim-of-type-nameidentifier-or-identityprovider-was-not-present-on-provided-claimsidentity/ – Hopeless Jun 26 '17 at 22:06

1 Answers1

0

Check and update your Global.asax.cs file with following code,You need to add AntiForgeryConfig.

namespace [Your-Project-Name] { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; } } }

Zealous System
  • 2,080
  • 11
  • 22