10

How should one carry out CRUD operations on a SQL Server database using C#?

For example, let's say there is a DB table Employees with these columns:

EmployeeID, FirstName, PostalCode

and I wish to post a new employee with info to that database. What would be an efficient method to accomplish this?

My current HttpPost:

namespace API.Controllers
{
    public class EmployeesController : ApiController
    {
        [HttpPost]
        public void AddEmployee (Employee employee)
        {
            SqlConnection myConnection = new SqlConnection();
            myConnection.ConnectionString = @"Server=.\servername;Database=Northwind;User ID=Username;Password=password;";

            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "INSERT INTO Employee (EmployeeID,FirstName,PostalCode) Values (@EmployeeID, @FirstName, @Zip)";

            sqlCmd.Parameters.AddWithValue("@EmployeeID", employee.EmployeeID);
            sqlCmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
            sqlCmd.Parameters.AddWithValue("@Zip", employee.Zip);

            myConnection.Open();
            int rowInserted = sqlCmd.ExecuteNonQuery();
            myConnection.Close();
        }
    }
}

And here is the Employee model:

namespace API.Models
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public int Zip { get; set; }
    }
}

When I test my API with Fiddler with the following input:

{ "EmployeeID":91, "FirstName":"Vader", "Zip":94221}

I get this error:

HTTP/1.1 415 Unsupported Media Type

and nothing is inserted into the database.

Any guidance would be greatly appreciated.

WebApiConfig.cs:

namespace API
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

The raw error message generated, as per request:

HTTP/1.1 415 Unsupported Media Type

Cache-Control: no-cache

Pragma: no-cache

Content-Type: application/json; charset=utf-8

Expires: -1

Server: Microsoft-IIS/10.0

X-AspNet-Version: 4.0.30319

X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcYW1lc2tvXGRvY3VtZW50c1x2aXN1YWwgc3R1ZGlvIDIwMTVcUHJvamVjdHNcQVBJXEFQSVxhcGlcRW1wbG95ZWVzXEFkZEVtcGxveWVl?=

X-Powered-By: ASP.NET

Date: Fri, 22 Jul 2016 15:33:06 GMT

Content-Length: 986

{"Message":"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.",

"ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Employee' from content with media type 'application/octet-stream'.",

"ExceptionType":"System.Net.Http.UnsupportedMediaTypeException",

"StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

7
  • 6
    What's your Content-Type header? application/json?
    – Jamie Rees
    Jul 22, 2016 at 15:54
  • Yes. My program then runs on localhost:55239, and I access my POST with localhost:55239/api/Employees/AddEmployee. Jul 22, 2016 at 16:00
  • Can you post your RouteConfig?
    – Jamie Rees
    Jul 22, 2016 at 16:01
  • Posted my WebApiConfig that generates in VisualStudio. I just realized that I must have deleted the RouteConfig.cs that VS creates. I'll try to add it back and see what happens. Jul 22, 2016 at 16:15
  • Please add the raw request posted through Fiddler.
    – venerik
    Jul 22, 2016 at 20:21

1 Answer 1

1

How are you passing the JSON Input? It needs to be through the request body with with request type application/json

you can specify you route as

"api/{controller}/{action}/{id}"

and then when calling the API url would be

http://localhost:63433/api/Employees/AddEmployee

notice Controller is not part of the URL

In the request body put

{ "EmployeeID":91, "FirstName":"Vader", "Zip":94221}

make the request type as Post and request body as application/json

you may test your api from a client tool like postman see screen

PostMan

If you can post ur client code may be I can check it.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.