简体   繁体   中英

c# HTTP Post IHttpActionResult

I have two httppost method one is taking an a concrete class with is working fine. The other one is taking in an interface. When I use postman I get null for the interface method.Should I be able to send a model class to an interface do I need to use custom model binder and if I do where do I need to add it?

public IHttpActionResult InsertData([FromBody] DataLog _datalog)

public IHttpActionResult Insert([ModelBinder(typeof(IDataLog))] IDataLog _log)

I think this would answer your question as well.

Interfaces

Reason why you cannot use interface as an object is because there are no public accessors for them. They also cannot have fields. It is just signature of the properties, and methods.

Interfaces

  1. cannot have implementation
  2. cannot have modifiers public
  3. cannot have virtual

Classes

Each class you define have public properties that have getters and setters. Setters are what sets the values of these public properties. You can use the interfaces and extend them to classes and use these classes as objects to receive the data

Good read about defining and implementing interfaces

Custom Model Binding in ASP with examples

I don´t know if i understand your question. Anyway regarding the code i must say:

  1. Do not use '_' to named your variables, classes, parameters...it is not CLS compliant. https://docs.microsoft.com/en-us/dotnet/api/system.clscompliantattribute?view=netframework-4.8

  2. Maybe you can use the letter 'D' following the SOLID principle. D as Dependency Inversion using the IOC to Dependency Injection. https://en.wikipedia.org/wiki/SOLIDhttps://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1

  3. In case that you have only one return type within your method, instead of using generic ActionResults types you can do something like, just to understand the logic:

Instead of:

public ActionResult Index()
{
    return View();
}

Do this:

public ViewResult Index()
{
    return View();
}

Difference Between ViewResult() and ActionResult()

  1. Do Async await (TAP ) pattern. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

  2. Instead of:

     public IHttpActionResult InsertData([FromBody] DataLog _datalog)

    Make the code to compile faster like this, adding the HttpPost attribute, even knowing this is a POST action:

    Do this:

     [HttpPost] public IHttpActionResult InsertData([FromBody] DataLog _datalog)

Hope those good practices helps you somehow! :)

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