0

I have begun writing an ASP.NET Web API for an app that I am building. I have set up a MongoCRUD.cs class to save data from POST requests made by the app to a MongoDB database (and other CRUD actions).

I (following a beginner tutorial), also set up a Submission.cs model class to act as a blueprint for the objects I wanted to save to the database. However, now that I have implemented the InsertRecord() method in MongoCRUD.cs, I cannot see a use for this model.

MongoCRUD.cs:

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPI.Services
{
    public class MongoCRUD
    {
        private IMongoDatabase db;

        public MongoCRUD(string database)
        {
            var client = new MongoClient();
            db = client.GetDatabase(database);
        }

        public void InsertRecord<T>(string table, T record)
        {
            var collection = db.GetCollection<T>(table);
            collection.InsertOne(record);
        }
    }
}

Submission.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Web;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace WebAPI.Models
{
    public class Submission
    {
        [BsonId]
        public string SubId { get; set; }
        public string Url { get; set; }
        public string Text { get; set; }
    }
}

SubmissionsController.cs:

using WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Services;
using System.IO;
using System.Web.Script.Serialization;

namespace WebAPI.Controllers
{
    public class SubmissionsController : ApiController
    {
        MongoCRUD db = new MongoCRUD("myDb");
    
        Submission[] submission = new Submission[] {
            new Submission { SubId = "test", Url = "test", Text = "test" };
        };

        public IEnumerable<Submission> GetAllSubmissions()
        {
            //add MongoCRUD functionality for load record
            return submission;
        }

        public IHttpActionResult GetSubmission(string id)
        {
            //add MongoCRUD functionality for load record
            return Ok();
        }

        public IHttpActionResult PostSubmission(object body)
        {
            //validate body
            db.InsertRecord("Submissions", body);
            return Ok();
        }
    }
}

As you can see at PostSubmission(), the body of the POST request can be saved to the database directly, so my question is what is the benefit of using a model such as Submission.cs instead of just using the object type?

I'm having some trouble traversing the body object to access its values (for carrying out validation etc), so my only guess is that using a model makes it easier to access values?

1 Answer 1

1

object is the base type for all classes (See - https://learn.microsoft.com/en-us/dotnet/api/system.object?view=netcore-3.1).

C# is an object-orientated language so we try to model classes based on our business domain, this makes it easier to reason about the code.

Like you said you can have models that can be used to validate the incoming data into the controller, also you might want to add extra methods on the models that related to your business domain.

For example

class CreditCard
{
    string CardNumber { get;set; }
    string Csv { get;set; }

    bool ValidateChecksum()
    { }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Okay, that is much more clear now, thank you. If I would like to post some data to my API, how would I save it as an instantiation of the Submission.cs class instead of just saving it as its base object type. If I simply change out the object body parameter to Submission body and then send that data to the database, it will timeout. If I run System.Diagnostics.Debug.WriteLine(body) it just returns WebAPI.Models.Submission in the console. There is something missing that is stopping it from working, can you see what it is?
You might need the [FromBody] attribute on your argument. public IHttpActionResult PostSubmission([FromBody] Submission body)
It appears it was timing out because I couldn't connect to my server. When I used [FromBody] attribute it does save the properties of the Submission model but all of the values are null, do I need to match they property names in the data that I post with the model in my API?
Yes the name will have to match, unless you use [JsonPropertyName("prop-name"] or [JsonProperty(Name="prop-name") depending on what you've got configurated - stackoverflow.com/a/58299628/4079967
Ok. I will give it a go soon, thanks for all of your help :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.