ASP.NET Web API 自定义发布操作不起作用

B. 赫尔斯霍夫

所以我的 API 中有一个 GebruikerController。Gebruiker 是荷兰语 User 的意思,这个控制器的作用是让用户登录、获取用户列表、添加用户并获取特定用户。但是我在为简单的登录功能引入自己的自定义post方法时遇到了一个问题。每当我从 PostMan 向函数发送一些数据时,我都会得到以下响应:

{"id":["值“登录”无效。"]}

我用这个网址访问它:

http://localhost:52408/api/gebruikers/login

这是我的控制器:

[Produces("application/json")]
[Route("api/Gebruikers")]
public class GebruikersController : Controller
{
    private readonly flowerpowerContext _context;

    public GebruikersController(flowerpowerContext context)
    {
        _context = context;
    }

    // GET: api/Gebruikers
    [HttpGet]
    public IEnumerable<Gebruiker> GetGebruiker()
    {
        return _context.Gebruiker;
    }

    // GET: api/Gebruikers/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetGebruiker([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var gebruiker = await _context.Gebruiker.SingleOrDefaultAsync(m => m.Id == id);

        if (gebruiker == null)
        {
            return NotFound();
        }

        return Ok(gebruiker);
    }

    [Route("api/gebruikers/login")]
    [HttpPost]
    public async Task<IActionResult> PostLogin([FromBody] string email, [FromBody] string password)
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if(GebruikerVerify(email, password))
        {
            var gebruiker = await _context.Gebruiker.FirstOrDefaultAsync((g) => (g.GebruikerEmail == email && g.GebruikerWachtwoord == password));
            return Ok(gebruiker);
        }
        else
        {
            return BadRequest("invalid data");
        }
    }

    // PUT: api/Gebruikers/5
    [HttpPut("{id}")]
    public async Task<IActionResult> PutGebruiker([FromRoute] int id, [FromBody] Gebruiker gebruiker)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != gebruiker.Id)
        {
            return BadRequest();
        }

        _context.Entry(gebruiker).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!GebruikerExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Gebruikers
    [HttpPost]
    public async Task<IActionResult> PostGebruiker([FromBody] Gebruiker gebruiker)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Gebruiker.Add(gebruiker);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetGebruiker", new { id = gebruiker.Id }, gebruiker);
    }

    // DELETE: api/Gebruikers/5
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteGebruiker([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var gebruiker = await _context.Gebruiker.SingleOrDefaultAsync(m => m.Id == id);
        if (gebruiker == null)
        {
            return NotFound();
        }

        _context.Gebruiker.Remove(gebruiker);
        await _context.SaveChangesAsync();

        return Ok(gebruiker);
    }

    private bool GebruikerExists(int id)
    {
        return _context.Gebruiker.Any(e => e.Id == id);
    }

    private bool GebruikerVerify(string email, string wacthwoord)
    {
        if(_context.Gebruiker.Any(e => e.GebruikerEmail == email))
        {
            Gebruiker gebruiker = _context.Gebruiker.FirstOrDefault(e => e.GebruikerEmail == email);
            if(wacthwoord == gebruiker.GebruikerWachtwoord)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
}

下面的代码是我的登录代码,在上面的代码中也可以看到。

        [Route("api/gebruikers/login")]
    [HttpPost]
    public async Task<IActionResult> PostLogin([FromBody] string email, [FromBody] string password)
    {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if(GebruikerVerify(email, password))
        {
            var gebruiker = await _context.Gebruiker.FirstOrDefaultAsync((g) => (g.GebruikerEmail == email && g.GebruikerWachtwoord == password));
            return Ok(gebruiker);
        }
        else
        {
            return BadRequest("invalid data");
        }
    }

    private bool GebruikerVerify(string email, string wacthwoord)
    {
        if(_context.Gebruiker.Any(e => e.GebruikerEmail == email))
        {
            Gebruiker gebruiker = _context.Gebruiker.FirstOrDefault(e => e.GebruikerEmail == email);
            if(wacthwoord == gebruiker.GebruikerWachtwoord)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

我对此很陌生,我对我在这里做错了什么一无所知。有人可以帮我解决这个问题吗?

恩科西

这是路由问题。由于控制器上的路由前缀,您正在点击GetGebruiker它预计id是 aint但它看到的是"login"字符串。

NextFromBody只能在动作参数中使用一次。将这些参数合并到一个模型中,然后使用该FromBody属性。

public class LoginModel {
    [Required]
    public string email { get; set; }
    [Required]
    public string password { get; set; }
}

请注意用于演示映射路由的注释。

[Produces("application/json")]
[Route("api/Gebruikers")]//route prefix for this controller
public class GebruikersController : Controller {
    //...code removed for brevity

    // GET: api/Gebruikers
    [HttpGet]
    public IEnumerable<Gebruiker> GetGebruiker() {
        //...code removed for brevity
    }

    // GET: api/Gebruikers/5
    [HttpGet("{id:int}")] // Note the route constraint
    public async Task<IActionResult> GetGebruiker([FromRoute] int id) {
        //...code removed for brevity
    }

    // POST: api/Gebruikers/login
    [HttpPost("login")]
    public async Task<IActionResult> PostLogin([FromBody] LoginModel login) {
        if(!ModelState.IsValid) {
            return BadRequest(ModelState);
        }

        if(GebruikerVerify(login.email, login.password)) {
            //...code removed for brevity
        } else {
            return BadRequest("invalid data");
        }
    }

    // PUT: api/Gebruikers/5
    [HttpPut("{id:int}")]
    public async Task<IActionResult> PutGebruiker([FromRoute] int id, [FromBody] Gebruiker gebruiker) {
        //...code removed for brevity
    }

    // POST: api/Gebruikers
    [HttpPost]
    public async Task<IActionResult> PostGebruiker([FromBody] Gebruiker gebruiker) {
        //...code removed for brevity
    }

    // DELETE: api/Gebruikers/5
    [HttpDelete("{id:int}")]
    public async Task<IActionResult> DeleteGebruiker([FromRoute] int id) {
        //...code removed for brevity
    }

    //..code removed for brevity
}

参考

ASP.NET Core 中的路由#Route Constraint Reference

路由到控制器操作

模型绑定

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

按ID删除行在Asp.net核心Web API + Angular 9中不起作用

单个路由的ASP.NET Web API自定义IHttpControllerSelector

具有自定义身份验证的ASP.NET Web API

ASP.net Web API 2路由属性不起作用

自定义ASP.NET Web API帮助页面的“资源描述”部分

使用angularJS的ASP.NET Web API调用自定义方法

带有OWIN的ASP.NET Web Api-自定义身份验证

ASP.Net Core Web Api中的异步视频流不起作用

自定义身份验证ASP.NET Core Web API

ASP.NET Core处理Web API中的自定义响应/输出格式的方法

返回的自定义状态代码在ASP.Net Web API中不起作用

ASP.NET Core Web API自动JSON参数反序列化不起作用

asp.net Web API csv助手写入流不起作用

ASP.Net Core Web API自定义路由不起作用

ASP.NET Core 3 Web Api发布请求不起作用

JWT承载令牌授权不起作用ASP Net Core Web API

ASP.NET Core 3.1 Web API基于角色的授权不起作用

ASP.Net Web API2-当API返回布尔值时不起作用

ASP.NET Core自定义中间件重定向到操作不起作用

ASP Net Core Web API自定义模型验证

ASP.NET Web Api自定义参数名称

ASP.NET Web API XmlFormatter不起作用,回退到JsonFormatter

使用AngularJS 1.4.7服务调用ASP.NET Web API不起作用

在asp.net Web API中找不到HTTP自定义异常

在针对Web API Asp.net的自定义过滤器中获取WebHostHttpRequestContext

ASP.Net Web API操作结果

asp.net web api 自定义方法操作类型 GET by id return 404

ASP.NET 核心 Web API 模板的 PUT、DELETE 不起作用(错误 404)

ASP.NET Core 3.1 Web API - 自定义 json