json字符串未正确解析

时间:2016-07-13 14:48:28

标签: c# json asp.net-mvc

我正在使用Rest Api。当用户点击从MVC应用程序登录但我一直收到错误

时,我发送用户名和密码
  

400错误请求

现在我通过代码调试并实现了解析为api的字符串如下

"{\"username\":\"email@somedomain.com\",\"password\":\"mypassword\"}"

所以我决定从字符串中删除\,如下所示:

string jsonString = JsonString(model.Email, model.Password);
string data = jsonString.Replace(@"\", "");

但无论出于何种原因,都不会删除反斜杠:/该字符串应解析为:

{"username":"email@somedomain.com","password":"mypassword"}

以下是完整代码:

HttpClient client = new HttpClient();

client.BaseAddress = new Uri("myurl");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

string jsonString = JsonString(model.Email, model.Password);
string data = jsonString.Replace(@"\", "");

HttpContent content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync("api/Account/Login", content).Result;

 if (messge.IsSuccessStatusCode)
 {
    return RedirectToLocal(returnUrl);
 }
 else
 {
   ModelState.AddModelError("", "Invalid login attempt.");
   return View(model);
 }

JsonString方法如下:

private string UserString(string us, string ps)
{
   var json = new JavaScriptSerializer().Serialize(
     new
     {
        username = us,
        password = ps
     });

  return json;
}

api /帐户/登录方法如下所示

[AllowAnonymous]
[Route("Login")]
public async Task<IHttpActionResult> Login(UserModel userModel)
{
    if (!ModelState.IsValid)
    {
       return BadRequest(ModelState);
    }
    IdentityUser result = await _repo.FindUser(userModel.UserName, userModel.Password);

    return Ok();
}

找到FindUser方法看起来像这样

public async Task<IdentityUser> FindUser(string userName, string password)
{
    IdentityUser user = await _userManager.FindAsync(userName, password);

    return user;
}

2 个答案:

答案 0 :(得分:0)

您无法删除\字符。它是特殊字符的转义字符,不能是字符串的正常部分,在这种情况下“是字符串的开头和字符串结尾。当你需要使用”字符串内部时,你必须在之前插入\。因此结果是“。”请参阅c#specs here。导致400的问题可能在其他地方。你能提供api /帐户/登录方法吗?

答案 1 :(得分:0)

你可以在这里删除很多代码。

    using (var httpClient = new HttpClient())
    {
        httpClient.PostAsJsonAsync("<your full url>", new UserModel { Email = "whatever", Password = "password" });
    }

PostAsJsonAsync将处理序列化模型,并设置http调用。

PostAsJsonAsync是Web Api Client Nuget包的一部分。

我还会在Login方法中设置一个断点,以准确找出Login方法的模型错误。

相关问题