I have a DTO:
using Microsoft.AspNetCore.Mvc;
using ProductManager.Core.Domain.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProductManager.Core.DTO
{
public class ProductAddRequest
{
[Required(ErrorMessage = "Name cant't be blank")]
[MinLength(3), MaxLength(30)]
[DataType(DataType.Text)]
[Remote(action: "IsProductAlreadyRegistered", controller: "ProductsController", ErrorMessage = "Product with this name already exists")]
public string Name { get; set; } = "";
[Required(ErrorMessage = "Description cant't be blank")]
[MinLength(3), MaxLength(30)]
[DataType(DataType.Text)]
public string Description { get; set; } = "";
[Required(ErrorMessage = "Category cant't be blank")]
[MinLength(3), MaxLength(30)]
[DataType(DataType.Text)]
public string Category { get; set; } = "";
public Product ToProduct()
{
return new Product { Name = Name, Description = Description, Category = Category };
}
}
}
and there are attributes to validate the model.
I have a service:
public async Task<ProductAddResponse> AddProduct(ProductAddRequest? productAddRequest)
{
if (productAddRequest == null)
{
throw new ArgumentNullException(nameof(productAddRequest));
}
Product product = productAddRequest.ToProduct();
product.ProductId = Guid.NewGuid();
await _productRepository.AddProduct(product);
return product.ToProductResponse();
}
and the controller:
[HttpPost]
[Route("[action]")]
// endpoint POST Products/create
public async Task<IActionResult> Create(ProductAddRequest productAddRequest) {
if (productAddRequest == null)
{
return BadRequest("ProductAddRequest is null");
}
if (!ModelState.IsValid) {
string errors = string.Join("n", ModelState.Values.SelectMany(value => value.Errors).Select(err => err.ErrorMessage));
return BadRequest(errors);
}
ProductAddResponse productAddResponse = await _productAdderService.AddProduct(productAddRequest);
return Ok(productAddResponse);
}
and the method that is used by remote function:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> IsProductAlreadyRegistered(string productName)
{
/* Product? registeredProduct = await _productGetterService.GetProductByProductName(productName);
if (registeredProduct == null)
{
return Json(true); //valid
}
else
{
return Json(false); //invalid
}
*/
throw new BadHttpRequestException("Bad request!");
}
}
the code is commented just to check if the validation is invoked.
The problem is that the validation model using Remote is not being remote. I can add any product name, even if it is already registered.
In fact, any add request should be cancelled by the exception, but i can add new products.
Why this function
IsProductAlreadyRegistered
is not getting invoked?
I tried changing ProductsController to Products and it didnt work.