获取自定义响应帖子请求

时间:2019-06-10 07:52:24

标签: c# reactjs .net-core

我通过将数据通过FormData()发送到后端中的操作来登录系统中的用户。用户登录,一切都很好。我想将响应(字符串,Json)发送回前端。

[Route("login")]
[HttpPost]
public async Task<ActionResult> LoginAsync(string username, string password)
{
    await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);

    var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

    if (result.Succeeded)
    {
        return new JsonResult("Succeeded", new JsonSerializerSettings());
        // or return new[] { user.DisplayName, user.Role };
    }

    return new JsonResult("Failed", new JsonSerializerSettings());
    //return Content("Failed");
}

在前端,我希望看到传递的字符串或json,但我将其作为获取的响应。

Response {type: "basic", url: "https://ip/api/sampledata/login", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "https://ip/api/sampledata/login"

1 个答案:

答案 0 :(得分:0)

.net核心,您不想返回JsonResults。

阅读以下文章 https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.2

[Route("login")]
[HttpPost]
public async Task<ActionResult> LoginAsync(string username, string password)
{
    await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);

       var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

        if (result.Succeeded)
        {
            return Ok(user); // your object
        }

        return NotFound();
    }