我通过 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());
}
在前端,我希望看到传递的字符串或 json,但我将其作为 fetch 的响应得到。
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"
最佳答案
您可以只使用 ContentResult
返回纯字符串:
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 Content("Failed");
}
ContentResult
默认情况下返回 text/plain
作为其 contentType。
关于javascript - 发布请求后返回自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56506672/