Deepak Mishra
Deepak Mishra

Reputation: 3183

How to disallow a post method from Get method in Web API?

I am just learning about WebAPIs and curious if we can reuse the Post method inside get method or it just violates the coding standards. How can we test if this violation is already done by someone?

 // GET api/values/5
    public string Get(int id)
    {
        var value= vc.Values.Where(v => v.Id == id).Select(v => v.Value1).SingleOrDefault(); 
        if (value==null) Post("New Value",id);
        return vc.Values.Where(v => v.Id == id).Select(v => v.Value1).SingleOrDefault();
    }

    // POST api/values
    public void Post([FromBody]string value, int id = 0)
    {
        vc.Values.Add(new Value { Id=id,Value1 = value });
        vc.SaveChanges();
    }

Upvotes: 0

Views: 103

Answers (1)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

These are 2 questions, not one.

Reusing code like this is a recipe for disaster. You can keep your endpoints very slim by moving the code into a library for example. Then you can simply call these new methods from the endpoints and this takes care of the code reuse part.

In terms of how you detect such issues, well, I wouldn't expect a tool to do it for you. You need a mature SDLC, you need code reviews and analysis on what you have already.

Upvotes: 1

Related Questions