简体   繁体   中英

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();
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM