【发布时间】:2018-05-03 06:20:08
【问题描述】:
我正在调用这样的 Web API 方法:
$.post("/api/attendances", { gigId: button.attr("data-gig-id") })
.done(function() {
button.removeAttr("btn-default")
.addClass("btn-primary")
.text("going");
})
.fail(function() {
alert("something went wrong");
});
Web API 类如下所示:
[Authorize]
public class AttendancesController : ApiController
{
private ApplicationDbContext _context;
public AttendancesController()
{
_context = new ApplicationDbContext();
}
[HttpPost]
public IHttpActionResult SaveAttenance(AttendanceDto dto)
{
string userId = User.Identity.GetUserId();
if (_context.Attendances.Any(a => a.GigId == dto.GigId && a.AttendeeId == userId))
{
return BadRequest();
}
_context.Attendances.Add(new Attendance()
{
GigId = dto.GigId,
AttendeeId = userId
});
_context.SaveChanges();
return Ok();
}
}
我正在使用匿名用户测试调用,当调用该方法时,我得到状态码 200,这不是我所期望的。我也收到了这个:
responseText :"{"Message":"授权已被拒绝 要求。”}” 状态:200 状态文本:“确定”
为什么 Authorize 属性没有返回与 responseText 匹配的状态代码?在我的例子中,无论用户是否被授权,.done 函数中的 JavaScript 代码都会执行。任何指导表示赞赏。
更新:如果有帮助,这是我的 web.config 的链接:https://pastebin.com/B26QGjv8
【问题讨论】:
-
确保您没有使用
[System.Web.Mvc.Authorize]而是使用[System.Web.Http.Authorize],同时添加WebApiConfig代码以便其他人可能会发现它对您有用。 -
@stom 更新帖子以包含 web.config
-
我的意思是
WebApiConfig.cs文件,它在你项目中的App_Start文件夹下。
标签: c# jquery asp.net-mvc asp.net-web-api