
本文旨在帮助开发者将 PHP 中接收 application/x-www-form-urlencoded 数据的 POST 请求转换为 C# .NET Core 中的等效实现。我们将探讨如何正确设置 Content-Type 头部,以及如何在 C# 中接收和处理来自第三方 API 的数据,从而避免 415 Unsupported Media Type 错误。
在 C# .NET Core 中,当与期望 application/x-www-form-urlencoded 数据的 API 交互时,需要确保正确设置请求的 Content-Type 头部,并正确处理接收到的数据。以下是如何解决 415 Unsupported Media Type 错误的详细步骤和示例代码。
1. 理解问题:Content-Type 头部的重要性
415 Unsupported Media Type 错误表明服务器无法理解客户端发送的数据格式。在你的例子中,第三方 API 期望接收 application/x-www-form-urlencoded 格式的数据,这通常是 HTML 表单提交时使用的格式。 如果你的 C# 代码没有正确设置 Content-Type 头部,或者发送了其他格式的数据(例如 JSON),服务器就会返回此错误。
立即学习“PHP免费学习笔记(深入)”;
2. C# 代码实现:接收 application/x-www-form-urlencoded 数据
首先,你需要修改你的 C# 控制器方法,以正确接收和处理来自 application/x-www-form-urlencoded 数据的请求。可以使用 [FromForm] 属性来绑定 POST 请求中的表单数据。
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Threading.Tasks;
namespace YourProject.Controllers
{
[ApiController]
[Route("[controller]")]
public class YourController : ControllerBase
{
[HttpPost("b_notice")]
[ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)]
public async Task<ActionResult> APIUrl([FromForm] string mm_id, [FromForm] string oo_id)
{
try
{
// 在这里处理接收到的 mm_id 和 oo_id 数据
string result = $"mm_id: {mm_id}, oo_id: {oo_id}";
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}解释:
3. 客户端请求:设置 Content-Type 头部
确保你的客户端(例如,使用 HttpClient)在发送 POST 请求时设置了 Content-Type 头部为 application/x-www-form-urlencoded。
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class ApiClient
{
public static async Task<string> PostData(string url, string mm_id, string oo_id)
{
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("mm_id", mm_id),
new KeyValuePair<string, string>("oo_id", oo_id)
});
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Error: {response.StatusCode}";
}
}
}
}解释:
使用示例:
string result = await ApiClient.PostData("https://your-api-endpoint/YourController/b_notice", "123", "456");
Console.WriteLine(result);4. 使用 Postman 进行测试
Postman 是一个非常有用的工具,可以用来测试你的 API。 在 Postman 中,你需要设置以下内容:
5. 注意事项
总结
通过正确设置 Content-Type 头部,并使用 [FromForm] 属性来绑定表单数据,你可以在 C# .NET Core 中成功接收和处理 application/x-www-form-urlencoded 格式的 POST 请求。 使用 Postman 等工具进行测试,可以帮助你验证你的 API 是否正常工作。 确保进行适当的数据验证和异常处理,以提高应用程序的健壮性和安全性。
以上就是将 PHP POST 请求转换为 C# 实现的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号