1

I am using asp.net core and I am calling async task ActionResult method from ajax. Its is running fine on local host but after hosting on IIS it throw 500 status code error.

But it is not calling this method is ajax code

This is ajax method:

$('.Savebtn').click(function () {
                    $.ajax({
                        url: '@Url.Action("Testing", "Home")',
                        data: "Test data",
                        type: 'POST', //POST if you want to save, GET if you want to fetch data from server
                        success: function (obj) {
                            // here comes your response after calling the server
                            alert('Suceeded');
                        },
                        error: function (obj) {
                            alert('Something happened');
                        }
                    });
            });

This is Controller method:

   [HttpPost]

   public async Task<IActionResult> Testing()
   {
       if (ModelState.IsValid)
         {
            try
            {
               return NotFound();
            }
            catch (Exception ex)
            {
                return NotFound();
            }

         }
            return View();
   }

Error Screen Shot

Nkosi
  • 235,767
  • 35
  • 427
  • 472
VIPIN DHINGRA
  • 31
  • 2
  • 7

3 Answers3

1

In Startup.cs file add service like this:

services.AddAntiforgery(options => options.HeaderName = "RequestVerificationToken");

In your cshtml file add:

@Html.AntiForgeryToken()

$.ajax({
    type: 'GET',
    url: '/home/Demo1',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("RequestVerificationToken",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    success: function (result) {
        alert(result);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(thrownError);
    }
});

And your method in Controller looks like this:

[HttpGet]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Demo1()
{
    //your code
    return new JsonResult(null);
}
Ramil Mammadov
  • 462
  • 6
  • 11
0

If you don't want [ValidateAntiForgeryToken] remove it and it will work. If you want it, then you have to pass the auto generated cookie value to validate as mentioned below, check this.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Testing()
{
   if (ModelState.IsValid)
    {
      try
      {
        await Task.Delay(100);

        return Ok();
      }
      catch (Exception ex)
      {

       return NotFound();

      }

    }
       return View();
 }

View:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
    {
        @Html.AntiForgeryToken()
    }

    <button class="Savebtn btn btn-success">Save</button>

Script:

    $(document).ready(function () {


        $('.Savebtn').click(function () {
            var form = $('#__AjaxAntiForgeryForm');
            var token = $('input[name="__RequestVerificationToken"]', form).val();

            $.ajax({
                url: '@Url.Action("Testing", "Home")',
                data: {
                    __RequestVerificationToken: token,
                    data: "Test data"
                },
                type: 'POST', //POST if you want to save, GET if you want to fetch data from server
                success: function (obj) {
                    // here comes your response after calling the server
                    alert('Suceeded');
                },
                error: function (obj) {
                    alert('Something happened');
                }
            });
    });

    })

</script>

Reference

Shaiju T
  • 6,201
  • 20
  • 104
  • 196
  • Hey Mr. Nimesh Gami bro. again i have problem to call that actionMethod on IIS but it is running fine on local host. i attched my error image. please check it – VIPIN DHINGRA Jan 15 '18 at 10:22
  • Welcome to SO, If you want to comment to Nimesh Gami then use @ check [this](https://meta.stackexchange.com/questions/43019/how-do-comment-replies-work) post to know how to reply to a specific user. Coming to your error, It gives 500 error because ,you are using `return NotFound();` instead use `return Ok();`. – Shaiju T Jan 15 '18 at 10:36
0

First change the URL to like 'Testing/Home' and Make sure you're passing data because if you don't it might throw 500 status code error.

In my case I wasn't passing any data I mean I was sending an empty form that was why. I thought it might help someone.

Miki
  • 157
  • 1
  • 8