【问题标题】:HTTP status code 200 but access denied. WebAPI ASP.NET MVCHTTP 状态代码 200 但访问被拒绝。 WebAPI ASP.NET MVC
【发布时间】: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


【解决方案1】:

这是因为尽管您使用了 [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...
    }
}

以此为参考,所有sn-ps均取自这里:

Handling exceptions in Web Api.

【讨论】:

  • 如果我们使用[Authorize] 属性,匿名用户将获得未经授权的status code : 401 但OP 得到200。您是否检查了示例WebApi 项目?
  • 是的,我的回答是根据的,请注意。另请注意:stackoverflow.com/questions/31205599/…
猜你喜欢
  • 2019-11-06
  • 2021-12-13
  • 2016-10-30
  • 1970-01-01
  • 2018-07-19
  • 2015-12-05
  • 2020-01-25
  • 2015-12-03
  • 2017-04-28
相关资源
最近更新 更多