[英]Powershell via ASP.Net - “The '=' operator failed: Access is denied.”
[英]HTTP status code 200 but access denied. WebAPI ASP.NET MVC
我正在調用這樣的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“:”對此請求的授權已被拒絕。“}” status:200 statusText:“ OK”
為什么Authorize屬性沒有返回與responseText相匹配的狀態代碼? 就我而言,無論用戶是否得到授權,.done函數中的JavaScript代碼都將執行。 任何指導表示贊賞。
更新:如果有幫助,這是指向我的web.config的鏈接: https : //pastebin.com/B26QGjv8
這是因為盡管您正在使用[Authorize]屬性,但是您對結果不做任何事情。
該方法可以按預期工作,正在發出請求,沒有被授權,但是您繼續在控制器中進行工作。
在控制器中處理異常:
重寫On Exception方法並創建一個異常屬性:
public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
}
}
然后在您的控制器中這樣調用它:
public class ProductsController : ApiController
{
[NotImplExceptionFilter]
public Contact GetContact(int id)
{
throw new NotImplementedException("This method is not implemented");
}
}
在您的WebApiConfig.cs中添加:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute());
// Other configuration code...
}
}
以此為參考,所有摘錄均摘自此處:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.