.net PostAsync忽略内容类型

hivapdat  于 2023-03-24  发布在  .NET
关注(0)|答案(1)|浏览(118)

I have following page

<%@ Page Title="Home Page" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BadgePunchClockLegacy._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
        
    <script>
        var Interval = setInterval(FactoryTimer, 1000);
        function FactoryTimer() {
            var currentDate = new Date();
            document.getElementById("FTimer").innerHTML = currentDate.toLocaleTimeString();
        }
    </script>

    <script type="text/javascript">
        function HideLabel() {
            document.getElementById('<%= LabelResult.ClientID %>').style.display = "none";
        }
        if ( <%=response_value ? "true": "false"%> ) {
            setTimeout("HideLabel();", 5000);
        }

    </script>

    <nav class="navbar navbar-light" style="background-color: skyblue">
      <h2>Badge Punch Clock</h2>
    </nav>

    <div class="jumbotron">
        <h1 style="text-align: center" id="FTimer"></h1>
    </div>

    <div class="container" >
      <div class="d-flex justify-content-center h-100">
        <div class="col-12">
            <div class="form-group text-center">
                <h2><label for="barcode">Codice badge</label></h2>
                <asp:TextBox ID="BarcodeInput" runat="server" BackColor="White" BorderColor="Black" BorderStyle="Solid" style="width:100%; height: 100%;"
                    OnTextChanged="Post_Click"></asp:TextBox> 
                <br /><br />
                <h2><asp:Label id="LabelResult" runat="server" /></h2>
            </div>
        </div>
      </div>
    </div>
</asp:Content>

And in code behind:

protected async void Post_Click(object sender, EventArgs e)
        {
            string url = Settings.Default.ApiAddress + "/api/login";
            BadgeInputDataDto dto = GetLoginDto();
            byte[] buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dto));
            ByteArrayContent byteContent = new ByteArrayContent(buffer);
            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = await client.PostAsync(url, byteContent);
            response_value = response.IsSuccessStatusCode;
            if (response_value)
            {
                OperationSuccessful(await response.Content.ReadAsStringAsync());
            }
            else
            {
                OperationFailed(await response.Content.ReadAsStringAsync());
            }
            await response.Content.ReadAsStringAsync();
        }

Problem is, I try to send content as JSON, but client.PostAsync causes internal server error. When I check content type, Content-Type header is x/www-form-urlencoded and sent content is this:
__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=LmnXD3B4JNCguOgFzIrYrQOfVH5L1sK4MBquAcQ%2F9IcSGmcKXOGWiL9J%2BBhR3DjiQoiNyYW%2FbJTCTu9Y8ptP7kMWIXYlc0Y3MdIHech%2B0Tw%3D&__VIEWSTATEGENERATOR=CA0B0334&__EVENTVALIDATION=lrq1HypynQzNR7z%2FV5lmzsLZXDbD7MDvaI691kn2WqkkibmGGBfiln4lFMGY%2Bc0zrhVM1fyChxTNNZpdB%2FMG78ZStZu8sh3VGPUAiusCputelEYSM3qvvIwAM3sGmdNI&ctl00%24MainContent%24BarcodeInput=SUPERVISOR
which is not what serialized object is.
How to make PostAsync actually use json content from buffer?

ffx8fchx

ffx8fchx1#

我想你可以试试这个语法

...
var contentData = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentData);
    
var dto = GetLoginDto();    
var json = JsonConvert.SerializeObject(dto) ;       
var content = new StringContent(json, Encoding.UTF8, "application/json");

var response = await client.PostAsync(url, content);

....

也许可以尝试使用Task而不是void

protected async Task Post_Click(object sender, EventArgs e)
{
..... //your code
}

相关问题