How to write an api action to create an entity in Web API

时间:2016-10-20 19:14:08

标签: asp.net asp.net-web-api http-post postman

I have a question regarding creating an HTTP POST action in WEB API (ASP.NET). Let's say I have an entity that is called 'category'

the Model class of it is like the following:

public class Category
    {
        // Navigation Properties
        [Required]
        public int CategoryID { get; set; }
        [Required]
        public string CategoryName { get; set; }
        public string CategoryDescription { get; set; }
        public DateTime DeletedAt { get; set; }

        // Scale Properties
    }

In the controller I put all the actions that I want to interact with this entity 'category'. One of the actions is to create a category (HTTP POST) like the following:

[HttpPost]
        [ActionName("createCategory")]
        public IHttpActionResult createCategory(Category category)
        {
            if (ModelState.IsValid){
                using (SqlConnection connection = WebApiApplication.reqeustConnection("ConStrMRR")) {
                    using (SqlCommand command = new SqlCommand("createCategory", connection)) {
                        try {
                            command.CommandType = CommandType.StoredProcedure;
                            command.Parameters.Add(new SqlParameter("@CategoryName", category.CategoryName));
                            command.Parameters.Add(new SqlParameter("@CategoryDescription", category.CategoryDescription));
                            command.ExecuteNonQuery();
                            return Ok("A category has been created");
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            connection.Close();
                        }
                    }
                }
            }
            return Content(HttpStatusCode.BadRequest, "Any object"); ;
        }

As you can see there is I am passing 2 parameters to the function.. however, I am not sure if this is the right way to do it.. In other languages I know that you can see the body parameters that it's been sent with the request through a global variable.

I am using POSTMAN to test my requests. I wanna send the url http://localhost:64611/api/categories/createCategory with body (raw) like the following

{
    "categoryName":"my category",
    "categoryDescription":"my description"
}

The response that I am getting from is

  "Message": "No HTTP resource was found that matches the request URI 'http://localhost:64611/api/categories/createCategory'.",
  "MessageDetail": "No action was found on the controller 'Categories' that matches the request."

The Route Template that I have is

config.Routes.MapHttpRoute(
                name: "defaultApiRoutes",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { id = @"\d+" }   // Only matches if "id" is one or more digits.
            );

My question is what should I change in my controller action to make this request work?

1 个答案:

答案 0 :(得分:0)

you have a number of options.

  1. go for a RESTful approach. This means you will have a Category controller with a method called POST.

public IHttpActionResult POST(Category category) { if ( ModelState.IsValid ) { //here you actually create the thing. } }

you access this on http://localhost:64611/api/category with a POST request

  1. You define a route:

    [HttpPost] [Route("createCategory")] public IHttpActionResult whatever(Category category) { // code here }

then you can post to http://localhost:64611/api/createCategory

Note how you use a model class, if you use it like I did, every property will be validated with the rules you defined.

I only mentioned RESTful because this is a standard used to develop APIs. You don't have to use it. The second option is probably what you're looking for. Just use the route attribute and you should be golden.

As for the body of the request, that's fine, JSON will work as expected. Try it with Postman.