0

I have the following defined HTTPPost Task in a controller which is usually called by AJAX

Task definition

 [HttpPost("MyFunction")]
 public async Task<JsonResult> MyFunction([FromBody] Model model){...}

AJAX

$.ajax({
                type: "POST",
                url: "/Controller/MyFunction",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },

                data: JSON.stringify({
                    ID: id,
                    Value: value,
                }),
...........

I would like to call the task defined above in a different .net class, and not AJAX. What would be the most efficient way to achieve this?

Thanks

unsatedw2
  • 11
  • 2
  • 1
    You probably don't want to do that, you want to use the functionality that the tasks provides for you. Instead you should create a seperate method/class that has this functionality and call it from the task and from the part of code where you want to call the task from – Gertjan Brouwer Jan 01 '20 at 14:46
  • Does this answer your question? [How to make HTTP POST web request](https://stackoverflow.com/questions/4015324/how-to-make-http-post-web-request) – devNull Jan 01 '20 at 14:50
  • @GertjanBrouwer The functionality is somewhat large and unique in its own controller, creating a seperate function for the same functionality would seem invalid – unsatedw2 Jan 01 '20 at 14:53
  • 1
    The reason I am saying this is because usually when you want to call a controller from your own application this means you need some functionality, but want to avoid duplicate code. The best thing to do is then to refactor that bit of functionality into a different method or class. – Gertjan Brouwer Jan 01 '20 at 15:03
  • If its code specific to the action, then it wouldn't be needed in 1 of your business layer classes. If its code that you would like to reuse, it should be centralised in your business layer. Your controller actions should always be kept light. Typical action would just instantiate a model, run a method and return view. The logic sits within the instantiated classes. If you are following SOLID principles, you would understand the need to plan for generic and custom logic – AbdulG Jan 10 '20 at 11:42
  • The biggest problem with what you are trying to do is that it goes against good practice and the 3 layered architecture – AbdulG Jan 10 '20 at 11:44

0 Answers0