我正在嘗試構建一個從 .NET 6.0 最小 API 服務器獲取資料的小型桌面應用程式 (.NET 6.0)。
API 服務器代碼為:
//app.MapPost("/show/", async Task<string> (string myName) =>
app.MapPost("/show/", async Task<string> (HttpRequest request) =>
{
//return await Task.FromResult(myName);
return await Task.FromResult(request.Query["myName"]);
});
郵遞員可以郵寄到
http://127.0.0.1:5400/show?myName=Srikanth S
并在未注釋和已注釋版本中得到答復。
桌面應用程式的回應物件有
狀態碼:500,原因短語:“內部服務器錯誤”
致電后
app.MapPost("/show/", async Task<string> (string myName)
版本,而它回應
StatusCode: 400, ReasonPhrase: 'Bad Request'
在回應物件和
查詢字串未提供必需的引數“string myName”
在結果物件上。
我的桌面應用程式只有這個簡單的代碼
private async void button1_Click(object sender, EventArgs e)
{
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("myName", "Srikanth S");
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync("http://127.0.0.1:5400/show", new FormUrlEncodedContent(content));
string result = await response.Content.ReadAsStringAsync();
Debug.WriteLine(result);
}
}
StringContent我嘗試了, FormUrlEncodedContent, Dictionary, KeyvaluePair...的排列組合;
看起來它沒有在HttpRequest版本中捕獲“myName”。
請問有什么指導或解決方案嗎?
更新:創建新的 .net core web api 專案(天氣預報示例),添加
app.MapPost("/show/", (string myName) =>
{
return myName;
});
以及嘗試過
app.MapPost("/show/", async (string myName) =>
{
return await Task.FromResult(myName);
});
桌面應用程式沒有變化,我在除錯輸出中得到這個,如下所示
Microsoft.AspNetCore.Http.BadHttpRequestException: Required parameter "string myName" was not provided from query string.
at Microsoft.AspNetCore.Http.RequestDelegateFactory.Log.RequiredParameterNotProvided(HttpContext httpContext, String parameterTypeName, String parameterName, String source, Boolean shouldThrow)
at lambda_method2(Closure , Object , HttpContext )
at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass36_0.<Create>b__0(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
--- End of stack trace from previous location ---
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Host: 127.0.0.1:5145
Content-Type: application/x-www-form-urlencoded
Content-Length: 17
非常感謝任何幫助。對于背景,我使用的是 Visual Studio 2022 社區版版本 17.3.6,dotnet 6.0.402
求救
uj5u.com熱心網友回復:
使用 Postman 檢查 API 方法時,可以看到請求 URL 中添加了引數。
Dictionary<string, string> content = new Dictionary<string, string>(); content.Add("myName", "Srikanth S"); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.PostAsync("http://127.0.0.1:5400/show", new FormUrlEncodedContent(content)); string result = await response.Content.ReadAsStringAsync(); Debug.WriteLine(result); }
但是在桌面應用中,引數被添加到請求體中,所以在這種場景下,API方法無法從請求URL中找到值,所以該值為null,會拋出例外。
為了解決這個問題,您可以嘗試通過 Query String 發送引數:在請求 URL 的末尾添加引數,如下所示:
var name = "Srikanth S";
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync($"http://127.0.0.1:5400?myName={name}", null);
string result = await response.Content.ReadAsStringAsync();
Debug.WriteLine(result);
}
API方法:
app.MapPost("/show/", async Task<string> (HttpRequest request) =>
{
//return await Task.FromResult(myName);
return await Task.FromResult(request.Query["myName"]);
});
或者您可以從請求正文中發送引數:在 API 方法中,您可以從表單中獲取引數。修改API方法如下:
app.MapPost("/show/", async Task<string> (HttpRequest request) =>
{
//return await Task.FromResult(myName);
return await Task.FromResult(request.Form["myName"]); //get value from form.
});
這時候,HttpClient 方法是這樣的:
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("myName", "Srikanth S");
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync("http://127.0.0.1:5400/show", new FormUrlEncodedContent(content));
string result = await response.Content.ReadAsStringAsync();
Debug.WriteLine(result);
}
請參閱以下螢屏截圖:

uj5u.com熱心網友回復:
PostAsync的第二個引數用于正文,而不是查詢字串資料。只需將myName查詢引數添加到 URL。
HttpResponseMessage response = await Client.PostAsync(
"http://127.0.0.1:5400/show?myName=Jose", // <----- Like this
new FormUrlEncodedContent(content)
);
uj5u.com熱心網友回復:
謝謝大家的指導和幫助。最后我破解了它:)希望這對每個人都有用。關鍵是要從 api 服務器上的請求正文中讀取發布資料。這是我的做法
app.MapPost("/show/", async (HttpRequest request) =>
{
var body = new StreamReader(request.Body);
string postData = await body.ReadToEndAsync();
Dictionary<string, dynamic> keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(postData) ?? new Dictionary<string, dynamic>();
// here after you can play as you like :)
return await Task.FromResult<string>(postData);
});
我的桌面應用程式代碼
private async void button1_Click(object sender, EventArgs e)
{
var client = new HttpClient();
using StringContent jsonContent = new(
JsonSerializer.Serialize(new {myName = "Srikanth S"}), Encoding.UTF8, "application/json");
using HttpResponseMessage response = await client.PostAsync("http://127.0.0.1:5145/show", jsonContent);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
// here after you can play as you like :)
Debug.WriteLine(jsonResponse);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/514888.html

