c# - 正在发送 HTTP 标头,但 Request.Headers 中不存在
问题描述
我的 api 端代码如下所示:
[HttpPost]
[Route("api/Login")]
public HttpResponseMessage ValidateLogin(UserModel user)
{
IEnumerable<string> customJsonInputString;
if (!Request.Headers.TryGetValues("Content-Type", out customJsonInputString))
return new HttpResponseMessage(HttpStatusCode.BadRequest);
var customJsonInputArray = customJsonInputString.ToArray();
var ProductsRequest =
Newtonsoft.Json.JsonConvert.DeserializeObject<UserModel>(customJsonInputArray[0]);
var result = _service.Fetch(
new UserModel
{
Username = user.Username,
Password = user.Password.GenerateHash()
}
);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
我正在尝试从位于同一解决方案中的单独项目中调用它:
[HttpPost]
public async Task<ActionResult> Login(UserLoginModel user)
{
UserModel data = new UserModel
{
Username = user.Username,
Password = user.Password
};
using (var client = new HttpClient())
{
var myContent = JsonConvert.SerializeObject(data);
var buffer = Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var endpoint = "http://localhost:55042/api/Login";
var response = await client.PostAsync(endpoint, byteContent);
throw new NotImplementedException();
}
}
我认为问题出在Request.Headers.TryGetValues("Content-Type", out customJsonInputString)
-s 第一个参数名称中,我已经在网上搜索过,但没有提出正确的描述/解释该参数名称应该是什么(好吧,我知道它是一个标题名称,但我试过了用“ContentType”也可以找到它,结果是一样的:“400 bad request”),所以我的问题是:
- 我究竟做错了什么?
- 我假设标题的名称是 "ContentType" 或 "Content-Type" 是错误的吗?
解决方案
尝试像这样更新您的代码:
using (var client = new HttpClient())
{
var myContent = JsonConvert.SerializeObject(data);
var endpoint = "http://localhost:55042/api/Login";
var response = await client.PostAsync(endpoint, new StringContent(myContent, Encoding.UTF8,"application/json"));
}
推荐阅读
- ios - 渐变层在 Xib 文件中的纵向模式下不起作用
- javascript - 使用 Cheerio 从 Youtube 抓取数据
- symfony - 加载时找不到类控制器
- node.js - 这种发送重置密码电子邮件的实现是否正确?
- asp.net-mvc - EF 未在 Visual Studio 2019 中显示数据库
- python-3.x - 为什么 print('a' > 'b') 为假而 print('a' > 'A') 为真?
- javascript - Javascript用自身的绑定版本替换函数是否不好
- amazon-web-services - AWS S3 无法使用预签名 URL 检索文档:无效日期(应该是自纪元以来的秒数)
- java - 异常:原因:org.springframework.beans.factory.BeanCreationException:创建名为“httpPutFormContentFilter”的bean时出错
- ios - 未从 firebase 添加 TableView 事件