从 Razor Pages 应用向 API 发送 HTTP 请求
Sending HTTP Requests to API from Razor Pages App
我正在创建一个向用户显示表单的应用程序。当用户提交表单时,我的应用程序获取这些值并将它们格式化为查询字符串。该字符串随后用于调用第三方 API。该应用程序是在 Visual Studio 2019 年使用 ASP.NET Core Razor Pages 模板用 C# 编写的。我首先尝试使用硬编码创建 HTTPClient 并向第三方 API 发送 HTTPRequestMessage控制台应用程序中的值,效果很好。但是,当将我的代码移动到 Razor Pages 应用程序以添加应用程序的前端时,我似乎无法让应用程序调用我创建的代码。由于我只获取表单值并将它们在查询字符串中传递给第三方 API,这不需要我定义自己的模型,因此我决定使用 Razor Pages 而不是 ASP.NET MVC。
这是我在应用程序中设置的 Index.cshtml 页面:
@page
@model IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
ViewData["Title"] = "Home page";
}
<div>
<form asp-page-handler="ProcessRequest" method="post">
<label for="FirstName">First Name:</label>
<input type="text" name="FirstName" value="" />
<label for="LastName">Last Name:</label>
<input type="text" name="LastName" value="" />
<label for="Email">Email:</label>
<input type="text" name="Email" value="" />
<button type="submit">Send Request</button>
</form>
</div>
如您所见,它只是一个具有三个输入字段的简单表单,没什么特别的。
包含模型逻辑的底层 Index.cshtml.cs 文件具有以下代码:
public class IndexModel : PageModel
{
static HttpClient myAppHTTPClient = new HttpClient();
public async void OnPostProcessRequestAsync()
{
string firstName, lastName, email;
string host = "https://thirdparty.app.com:443/";
string pathname = "path/to/api/endpoint/?operation=create";
firstName = "Test";
LastName = "User";
email = "TestUser@email.com";
string path = pathname + "&first_name=" + firstName + "&last_name=" + lastName + "&email=" + email;
string requestUrl = host + path;
HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
try
{
HttpResponseMessage responseMessage = await myAppHTTPClient.PostAsync(requestUrl, httpRequestMessage.Content);
HttpContent content = responseMessage.Content;
string message = await content.ReadAsStringAsync();
Console.WriteLine("The output from thirdparty is: {0}", message);
RedirectToPage();
}
catch (HttpRequestException exception)
{
Console.WriteLine("An HTTP request exception occurred. {0}", exception.Message);
}
}
}
ASP.NET Razor Pages 的文档说,当您的表单中有一个 asp-page-handler 标签助手时,提交表单将调用页面处理程序方法 OnPost[method_name]Async()
。在我的例子中,表单中的 <form asp-page-handler="ProcessRequest" method="post">
行应该调用 public async void OnPostProcessRequestAsync()
方法。但是,这并不像我想象的那样有效。我尝试在表单和提交按钮中使用不同的标签助手。有没有办法让 Razor 页面调用运行我的代码的方法。我知道我缺少 RedirectToPage() 方法,但我首先想让方法调用起作用。
尽管此线程中的两个人已经提出了答案,但我没有找到可以将他们的评论标记为已回答问题的方法。因此,为了公平起见并给予应有的信任,他们的建议使我能够修复我的代码。基本上,我错误地定义了页面处理程序方法。我将其定义为:
public async void OnPostProcessRequestAsync()...
但是,这种类型的应用程序需要页面处理程序方法来 return 像 Task.将 return 类型从 void 更改为 Task 时效果很好。我的猜测是,由于我异步定义此代码,因此 return 值必须是异步的。由于 Task<> class 用于线程(异步)代码,因此这可行。
我正在创建一个向用户显示表单的应用程序。当用户提交表单时,我的应用程序获取这些值并将它们格式化为查询字符串。该字符串随后用于调用第三方 API。该应用程序是在 Visual Studio 2019 年使用 ASP.NET Core Razor Pages 模板用 C# 编写的。我首先尝试使用硬编码创建 HTTPClient 并向第三方 API 发送 HTTPRequestMessage控制台应用程序中的值,效果很好。但是,当将我的代码移动到 Razor Pages 应用程序以添加应用程序的前端时,我似乎无法让应用程序调用我创建的代码。由于我只获取表单值并将它们在查询字符串中传递给第三方 API,这不需要我定义自己的模型,因此我决定使用 Razor Pages 而不是 ASP.NET MVC。
这是我在应用程序中设置的 Index.cshtml 页面:
@page
@model IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
ViewData["Title"] = "Home page";
}
<div>
<form asp-page-handler="ProcessRequest" method="post">
<label for="FirstName">First Name:</label>
<input type="text" name="FirstName" value="" />
<label for="LastName">Last Name:</label>
<input type="text" name="LastName" value="" />
<label for="Email">Email:</label>
<input type="text" name="Email" value="" />
<button type="submit">Send Request</button>
</form>
</div>
如您所见,它只是一个具有三个输入字段的简单表单,没什么特别的。
包含模型逻辑的底层 Index.cshtml.cs 文件具有以下代码:
public class IndexModel : PageModel
{
static HttpClient myAppHTTPClient = new HttpClient();
public async void OnPostProcessRequestAsync()
{
string firstName, lastName, email;
string host = "https://thirdparty.app.com:443/";
string pathname = "path/to/api/endpoint/?operation=create";
firstName = "Test";
LastName = "User";
email = "TestUser@email.com";
string path = pathname + "&first_name=" + firstName + "&last_name=" + lastName + "&email=" + email;
string requestUrl = host + path;
HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
try
{
HttpResponseMessage responseMessage = await myAppHTTPClient.PostAsync(requestUrl, httpRequestMessage.Content);
HttpContent content = responseMessage.Content;
string message = await content.ReadAsStringAsync();
Console.WriteLine("The output from thirdparty is: {0}", message);
RedirectToPage();
}
catch (HttpRequestException exception)
{
Console.WriteLine("An HTTP request exception occurred. {0}", exception.Message);
}
}
}
ASP.NET Razor Pages 的文档说,当您的表单中有一个 asp-page-handler 标签助手时,提交表单将调用页面处理程序方法 OnPost[method_name]Async()
。在我的例子中,表单中的 <form asp-page-handler="ProcessRequest" method="post">
行应该调用 public async void OnPostProcessRequestAsync()
方法。但是,这并不像我想象的那样有效。我尝试在表单和提交按钮中使用不同的标签助手。有没有办法让 Razor 页面调用运行我的代码的方法。我知道我缺少 RedirectToPage() 方法,但我首先想让方法调用起作用。
尽管此线程中的两个人已经提出了答案,但我没有找到可以将他们的评论标记为已回答问题的方法。因此,为了公平起见并给予应有的信任,他们的建议使我能够修复我的代码。基本上,我错误地定义了页面处理程序方法。我将其定义为:
public async void OnPostProcessRequestAsync()...
但是,这种类型的应用程序需要页面处理程序方法来 return 像 Task.将 return 类型从 void 更改为 Task 时效果很好。我的猜测是,由于我异步定义此代码,因此 return 值必须是异步的。由于 Task<> class 用于线程(异步)代码,因此这可行。