Mirko
Mirko

Reputation: 59

Validate a Action with ASP.NET Web API

In my solution i have three projects:

App.Model

In this project i have my models class and a single dbcontext (code first)

    public class Customer
{
    [Key]
    public int ID { get; set; }

    public string  Name { get; set; }
}

App.UI - MVC Project

Here, there are the controllers (Get method) and views

    public ActionResult Create()
    {
        return View();
    }

App.Validation - ASP.NET Web API Project

Here there are only controllers for validation (Post method).

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="ID,Name")] Customer customer)
    {
        if (ModelState.IsValid)
        {
            db.Customer.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(customer);
    }

When I call a post action from a controller in the UI project, I would the controller in API project perform validation of the UI Controller.

I have to change the routing rules in RouteConfig and WebApiConfig or I need pass the action as a parameter to the API?

Upvotes: 0

Views: 706

Answers (1)

Ronald
Ronald

Reputation: 1542

One way to do this is to call the API controller action from the UI controller action.

    [HttpPost]
    public ActionResult Create(Customer customer)
    {
        try
        {
            var json = JsonConvert.SerializeObject(customer);
            Encoding encoding = Encoding.UTF8;

            var requestBody = encoding.GetBytes(json)
            var uri = ""; // replace empty string with the uri of the web Api project

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Timeout = 999;
            request.ContentType = "application/json";
            request.Method = "put";
            request.ContentLength = requestBody.Length;
            request.GetRequestStream().Write(requestBody, 0, requestBody.Length);
            request.GetResponse();

            return RedirectToAction("Index");
        }
        catch (WebException e)
        {
            // handle exception
            return View(customer);
        }
    }

The web API action can be something like this:

[HttpPost]
public HttpResponseMessage Create(Customer customer)
{
    if (ModelState.IsValid)
    {
        db.Customer.Add(customer);
        db.SaveChanges();
        return Request.CreateResponse(HttpStatusCode.OK);
    }        
    else
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest);
    }
}

Upvotes: 1

Related Questions