• 首先415的官方解释是:对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝。
  • 也就是说我所准备的数据格式并不是后台代码使用的数据格式
  • 后台代码如下
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc; namespace JwtAuth.Controllers
    {
    using System.Security.Claims;
    using Microsoft.Extensions.Options;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    //添加dll的引用 Nuget Microsoft.AspNetCore.Authentication.JwtBearer;
    using System.IdentityModel.Tokens.Jwt;
    [Route("api/[controller]")]
    public class AuthController : Controller
    {
    public JwtSettings settings;
    public AuthController(IOptions<JwtSettings> jwtsettings)
    {
    settings = jwtsettings.Value;
    }
    [HttpPost]
    public IActionResult Token([FromBody]LoginInfo model)
    {
    if (ModelState.IsValid)
    {
    if (model.username == "cyao" && model.password == "")
    {
    //用户合法情况
    //添加授权信息
    var claims = new Claim[] { new Claim(ClaimTypes.Name, "cyao"), new Claim(ClaimTypes.Role, "admin") };
    var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var token = new JwtSecurityToken(
    settings.Issuer,
    settings.Audience,
    claims,
    DateTime.Now,
    DateTime.Now.AddMinutes(),//过期时间
    creds);
    return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
    }
    }
    return BadRequest();
    }
    }
    public class LoginInfo
    {
    [Required]
    public string username { get; set; }
    [Required]
    public string password { get; set; }
    }
    }
  • 使用POSTMan如何构造一个
    [FromBody]?错误示例.net core 学习小结之 PostMan报415-LMLPHP(图1.0)
  • 正确示例如下图2.0.net core 学习小结之 PostMan报415-LMLPHP(图2.0)
  • 或者使用图1.0的配置将后台代码参数的标签改成[FromForm]
05-28 14:18