error 400 当尝试以 POST 类型进行 AJAX 请求到函数 OnPostshiftDataUp 时发生。

huangapple go评论58阅读模式
英文:

error 400 when try to make ajax request with type post to function OnPostshiftDataUp

问题

I am working with Asp.Net Core Razor Pages. I get an error when trying to make an ajax request to access OnPostshiftDataUp.

ERROR: Failed to load resource: the server responded with a status of 400 ()

console.log(formdata) // serialize data

serverip=172.16.224.999&printername=Zebra2&Location=SupervisorOffice&__RequestVerificationToken=CfDJ8DvYZnvxyLVKi-zvp3jzTImPtgQsnvTBz4ot8mbln2lEaqGcaT_gzZ-KNNfuEBoqHYSBIdcahXL3LLuum4nfTi2oZDQj-PfodyDAVpa45rYEIb7EcRvHrMn71AyB8PMC6DrqvT8q3cCEcSlt1sYQJ-M

but the breakpoint does not catch this function, meaning it does not detect that there are breakpoints that must catch it.

The main purpose of the ajax request is to save data after updating data on the Bootstrap modal.

What I tried for my code:

  1. Function with type post on the page model:
public ActionResult OnPostshiftDataUp()
{
    return Content("msg");
}
  1. Ajax request to access function or action OnPostshiftDataUp:
$('#save-btn').click(function () {
    var formData = $('#edit-form').serialize();
    console.log(formData);

    $.ajax({
        url: '?handler=shiftDataUp',
        type: "POST",
        data: JSON.stringify(formData),
        success: function (result) {
            $('#edit-modal').modal('hide');
            location.reload();
        },
        error: function (xhr, status, error) {
            console.log(error);
        }
    });
});

Bootstrap modal then sends an ajax request when clicking the "Save" button:

<div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
    <!-- ... (modal content) ... -->
</div>
<table id="editbootstarp">
    <!-- ... (table content) ... -->
</table>
$(document).ready(function(){
    // ... (click event handler and ajax request) ...
});

If you continue to experience issues, please provide more specific information about the problem so that I can assist you further.

英文:

I am working with Asp.Net Core Razor Pages. I get an error when trying make ajax request to access OnPostshiftDataUp

ERROR : Failed to load resource: the server responded with a status of 400 () 

console.log(formdata) // serialize data

serverip=172.16.224.999&amp;printername=Zebra2&amp;Location=SupervisorOffice&amp;__RequestVerificationToken=CfDJ8DvYZnvxyLVKi-zvp3jzTImPtgQsnvTBz4ot8mbln2lEaqGcaT_gzZ-KNNfuEBoqHYSBIdcahXL3LLuum4nfTi2oZDQj-PfodyDAVpa45rYEIb7EcRvHrMn71AyB8PMC6DrqvT8q3cCEcSlt1sYQJ-M

but break point not catch this function meaning not detect there are breakpoint must catch it

the main purpose from ajax request is save data after update data on bootstrap model

what I try for my code

1- function with type post on page model

public ActionResult OnPostshiftDataUp()
        {

            
            return Content(&quot;msg&quot;);
           
        }

2- ajax request to access function or action OnPostshiftDataUp
ajax request i do it

$(&#39;#save-btn&#39;).click(function () {
                var formData = $(&#39;#edit-form&#39;).serialize();
                console.log(formData);
            
                $.ajax({
                    url: &#39;?handler=shiftDataUp&#39;,
                    
         
                    type: &quot;POST&quot;,
                  
                    data: JSON.stringify(formData),
            
                   
                    success: function (result) {
                     
                        $(&#39;#edit-modal&#39;).modal(&#39;hide&#39;);
       
                        location.reload();
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                });
            });

bootstrap model then send ajax request when click button save

&lt;div class=&quot;modal fade&quot; id=&quot;editshelflabelModal&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;userDetailsModalLabel&quot; aria-hidden=&quot;true&quot;&gt;
    &lt;div class=&quot;modal-dialog modal-dialog-centered&quot; role=&quot;document&quot;&gt;
        &lt;div class=&quot;modal-content&quot;&gt;
            &lt;h5 class=&quot;modal-title&quot; style=&quot;text-align:center;&quot;&gt;
                @*&lt;img src=&quot;@Url.Content(&quot;~/Img/UserProfile1.png&quot;)&quot; alt=&quot;ImageProfile&quot; style=&quot;width:22%;height:10%&quot; /&gt;*@

            &lt;/h5&gt;
            &lt;div class=&quot;modal-header&quot;&gt;
                &lt;h5 class=&quot;modal-title&quot; id=&quot;editshelflabelModaldata&quot; style=&quot;margin-left:200px;&quot;&gt;Hi,@TempData[&quot;UserID&quot;]&lt;/h5&gt;
                &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-label=&quot;Close&quot;&gt;
                    &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
                &lt;/button&gt;
            &lt;/div&gt;
            &lt;div class=&quot;modal-body&quot;&gt;
                  &lt;form id=&quot;edit-form&quot; method=&quot;post&quot;&gt;
                  @*  &lt;input type=&quot;hidden&quot; id=&quot;edit-id&quot; name=&quot;ShiftId&quot;&gt;*@
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;edit-server&quot;&gt;Server IP&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;edit-ip&quot; name=&quot;serverip&quot;&gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;edit-printer&quot;&gt;Printer Name&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;edit-printername&quot; name=&quot;printername&quot;&gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;edit-locationsdata&quot;&gt;Location Name&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;edit-Location&quot; value=&quot;save&quot; name=&quot;Location&quot;&gt;
                    &lt;/div&gt;
                &lt;/form&gt;
                @*&lt;div class=&quot;form-group row&quot;&gt;
                    &lt;label for=&quot;serverIp&quot; class=&quot;col-sm-1 col-form-label&quot; style=&quot;font-size:15px;font-family: &#39;Open Sans&#39;, sans-serif;font-weight: bold;&quot;&gt;Server IP&lt;/label&gt;
                    &lt;div class=&quot;col-sm-3&quot;&gt;
                        &lt;input id=&quot;serverIp&quot; asp-for=&quot;User.UserName&quot; readonly type=&quot;text&quot; class=&quot;form-control&quot; style=&quot; margin-left:10px;font-size:15px;font-family: &#39;Open Sans&#39; , sans-serif;font-weight: bold;&quot; maxlength=&quot;30&quot; /&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            

            &lt;/div&gt;
            &lt;div class=&quot;modal-footer&quot;&gt;
                &lt;button type=&quot;button&quot; class=&quot;btn btn-secondary&quot; data-bs-dismiss=&quot;modal&quot;&gt;Close&lt;/button&gt;
                &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot; id=&quot;save-btn&quot;&gt;Save changes&lt;/button&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

updated post

issue still exist after apply answer below :

error display Failed to load resource: the server responded with a status of 400 ()

so what i do to solve error

Last updated Post
issue until now not solved can you please help me by sending full sample with bootstrap model and jQuery and html table may be i have issue on some parts please

From code below request success done but function post PostshiftDataUp()
not cached or hit after click save button

Full code sample for what I try

program.cs
builder.Services.AddAntiforgery(o =&gt; o.HeaderName = &quot;XSRF-TOKEN&quot;);   
public class ShelfLabelPrinterSetUpModel : PageModel
{
[BindProperty]
public string serverip { get; set; }
[BindProperty]
public string printername { get; set; }
[BindProperty]
public string Location { get; set; }
public IActionResult OnPostshiftDataUp(string serverip, string printername, string location)
{
return new JsonResult(&quot;Success&quot;);
}
}
&lt;div class=&quot;modal fade&quot; id=&quot;editshelflabelModal&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;userDetailsModalLabel&quot; aria-hidden=&quot;true&quot;&gt;
&lt;div class=&quot;modal-dialog modal-dialog-centered&quot; role=&quot;document&quot;&gt;
&lt;div class=&quot;modal-content&quot;&gt;
&lt;h5 class=&quot;modal-title&quot; style=&quot;text-align:center;&quot;&gt;
&lt;/h5&gt;
&lt;div class=&quot;modal-header&quot;&gt;
&lt;h5 class=&quot;modal-title&quot; id=&quot;editshelflabelModaldata&quot; style=&quot;margin-left:200px;&quot;&gt;Hi,@TempData[&quot;UserID&quot;]&lt;/h5&gt;
&lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-label=&quot;Close&quot;&gt;
&lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
&lt;/button&gt;
&lt;/div&gt;
&lt;div class=&quot;modal-body&quot;&gt;
&lt;form id=&quot;edit-form&quot; method=&quot;post&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;edit-server&quot;&gt;Server IP&lt;/label&gt;
&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;edit-ip&quot; name=&quot;serverip&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;edit-printer&quot;&gt;Printer Name&lt;/label&gt;
&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;edit-printername&quot; name=&quot;printername&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;edit-locationsdata&quot;&gt;Location Name&lt;/label&gt;
&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;edit-Location&quot;  name=&quot;Location&quot;&gt;
&lt;/div&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot; id=&quot;save-btn&quot;&gt;Save changes&lt;/button&gt;
&lt;/form&gt;
&lt;a href=&quot;/&quot;&gt;&lt;i class=&quot;fas fa-sign-out-alt&quot;&gt;&lt;/i&gt; Sign Out&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;modal-footer&quot;&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-secondary&quot; data-bs-dismiss=&quot;modal&quot;&gt;Close&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;table id=&quot;editbootstarp&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;display:none;&quot;&gt;ID&lt;/th&gt;
&lt;th&gt;BranchType&lt;/th&gt;
&lt;th&gt;UserPC&lt;/th&gt;
&lt;th&gt;PrinterName&lt;/th&gt;
&lt;th&gt;ArabicConfig&lt;/th&gt;
&lt;th&gt;Status&lt;/th&gt;
&lt;th&gt;Location Name&lt;/th&gt;
&lt;th&gt;&gt;Action&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
@foreach (DataRow row in table.Rows)
{
&lt;tr&gt;
&lt;td style=&quot;display:none;&quot;&gt;@row[&quot;AutoID&quot;]&lt;/td&gt;
&lt;td&gt;@row[&quot;BranchType&quot;]&lt;/td&gt;
&lt;td&gt;@row[&quot;UserPC&quot;]&lt;/td&gt;
&lt;td&gt;@row[&quot;PrinterName&quot;]&lt;/td&gt;
&lt;td&gt;@row[&quot;ArabicConfig&quot;]&lt;/td&gt;
&lt;td&gt;@row[&quot;Status&quot;]&lt;/td&gt;
&lt;td&gt;@row[&quot;DisplayName&quot;]&lt;/td&gt;
&lt;td&gt;
&lt;button class=&quot;editbt&quot;   data.Location=&quot;@row[&quot;DisplayName&quot;]&quot; data.printername=&quot;@row[&quot;PrinterName&quot;]&quot; data.serverip=&quot;@row[&quot;UserPC&quot;]&quot;&gt;Edit&lt;/button&gt;
&lt;/td&gt;  
&lt;/tr&gt;
}
&lt;/tbody&gt;
&lt;/table&gt;
@section scripts {
&lt;script src=&quot;https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
$(document).ready(function(){
$(&#39;#editbootstarp tbody&#39;).on(&#39;click&#39;, &#39;tr&#39;, function () {
// Get the data from the clicked row
var rowData = $(this).children(&#39;td&#39;).map(function () {
return $(this).text();
}).get();
$(&#39;#editshelflabelModal #edit-ip&#39;).val(rowData[2]);
$(&#39;#editshelflabelModal #edit-printername&#39;).val(rowData[3]);
$(&#39;#editshelflabelModal #edit-Location&#39;).val(rowData[6]);
$(&#39;#editshelflabelModal&#39;).modal(&#39;show&#39;);
});
$(&#39;#save-btn&#39;).click(function () {
var formData = $(&#39;#edit-form&#39;).serialize();
console.log(formData);
$.ajax({
url: &#39;?handler=shiftDataUp&#39;,
type: &quot;POST&quot;,
beforeSend: function (xhr) {
xhr.setRequestHeader(&quot;XSRF-TOKEN&quot;,
$(&#39;input:hidden[name=&quot;__RequestVerificationToken&quot;]&#39;).val());
},
data:formData,
success: function (result) {
alert(result);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
});
});

image for more details
error 400 当尝试以 POST 类型进行 AJAX 请求到函数 OnPostshiftDataUp 时发生。

network tool browser gool chrome result also
Request URL:
https://localhost:7160/ShelfLabelPrinterSetUp?handler=shiftDataUp
Request Method:
POST
Status Code:
200
Remote Address:
[::1]:7160
Referrer Policy:
strict-origin-when-cross-origin

答案1

得分: 1

您之所以收到400 Bad Request错误是因为您未通过Razor Pages默认内置的反请求伪造检查。有关详细信息,请参阅:https://www.learnrazorpages.com/security/request-verification

当您将表单数据转换为JSON时,请求验证令牌将隐藏在请求体中,作为JSON负载的一部分。在这种情况下,Razor Pages无法读取令牌,因此您需要将请求验证令牌发送到标头中:

$.ajax({
    url: '?handler=shiftDataUp',
    type: "POST",
    contentType: "application/json",
    headers: {
        "RequestVerificationToken": $('[name="__RequestVerificationToken"]').val()
    },
    data: JSON.stringify(formData)
    ...

或者,不要将表单序列化为JSON。将其原样发送:

$.ajax({
    url: '?handler=shiftDataUp',
    type: "POST",
    data: $('#edit-form').serialize()
    ...
英文:

You are getting a 400 Bad Request because you are failing the anti-request forgery check which is built into Razor Pages by default: https://www.learnrazorpages.com/security/request-verification

When you convert the form data to JSON, the request verification token is hidden in the request body as part of the JSON payload. Razor Pages is unable to read the token in that condition, so you need to send the request verification token in the headers:

$.ajax({
url: &#39;?handler=shiftDataUp&#39;,
type: &quot;POST&quot;,
contentType: &quot;application/json&quot;,
headers: {
&quot;RequestVerificationToken&quot; : $(&#39;[name=&quot;__RequestVerificationToken&quot;]&#39;).val()
},
data: JSON.stringify(formData)
...

Alternatively, don't serialise the form to JSON. Send it as-is:

$.ajax({
url: &#39;?handler=shiftDataUp&#39;,
type: &quot;POST&quot;,
data: $(&#39;#edit-form&#39;).serialize()
...

huangapple
  • 本文由 发表于 2023年6月22日 19:00:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定