HTTP标头正在发送,但在Request.Headers中不存在

时间:2019-03-24 02:24:52

标签: c# asp.net asp.net-mvc asp.net-web-api

我的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)的第一个参数名称中,我已经在网上搜索过,但没有给出正确的描述/解释,该参数名称应该是什么(嗯,我明白了它是标题名称,但我也尝试使用“ ContentType”找到它,结果是相同的:“ 400错误的请求”),所以我的问题是:

  • 我在做什么错了?
  • 我假设标题的名称是“ ContentType”还是“ Content-Type”是错误的吗?

3 个答案:

答案 0 :(得分:0)

尝试像这样更新代码:

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"));
        }

答案 1 :(得分:0)

Content-Type标头位于Request.Content.Headers中。您可以使用当前代码获取标头值或检查Request.Content.Headers.ContentType属性是否等于null

//note added Content
if (!Request.Content.Headers.TryGetValues("Content-Type", out customJsonInputString))
    return new HttpResponseMessage(HttpStatusCode.BadRequest);

if (Request.Content.Headers.ContentType == null)
    return new HttpResponseMessage(HttpStatusCode.BadRequest);

ContentType属性等于null,即使设置了Content-Type标头却无效。

答案 2 :(得分:0)

我使用HttpWebRequest而不是HttpClient,遇到了更多问题,但最终所有问题都解决了。 How i chose to proceed and next problem which is already solved