-2

I have the generic BaseController like this:

public class BaseController<T> : Controller where T : BaseEntity
{
    protected readonly IRepository _repository;

    public BaseController(IRepository repository)
    {
        _repository = repository;
    }

    // POST: TController/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public virtual async Task<IActionResult> Create(T item)
    {
        try
        {
            if (ModelState.IsValid)
            {
                await _repository.AddAsync(item);

            }
            return RedirectToAction(nameof(Index));
        }
        catch
        {
            return PartialView();
        }
    }

Do I correctly override this action in the derived controller class

public class PaysController : BaseController<Pays>
{
    public PaysController(IRepository repository): base(repository) { }

    // POST: Pays/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public override async Task<IActionResult> Create([Bind("IDPays,Code,Nom")] Pays pays)
    {
        return await base.Create(pays);
    }

Especially, should I reuse the method attributes(like ValidateAntiForgeryToken), and will the binding Bind work in that case?

serge
  • 13,940
  • 35
  • 121
  • 205
  • It is not good idea to keep you EF code in controller. Think about creating a generic repository for this instead. – Serge Jan 16 '21 at 14:26

1 Answers1

1

Method attributes do not need to be reused on the overriden method:

var attributes = typeof(PaysController).GetMethod("Create").GetCustomAttributes(false);

Debug.Assert(attributes.Any(x => x.GetType() == typeof(HttpPostAttribute)));
Debug.Assert(attributes.Any(x => x.GetType() == typeof(ValidateAntiForgeryTokenAttribute)));

The binding Bind will work in the overrided method. You will need to mark the base controller as abstract, otherwise ASP.NET Core does not know, which controller and endpoint to choose and throws an exception:

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints

Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63