未经授权的webapi调用返回登录页面而不是401

如何配置我的mvc / webapi项目,以使从剃刀视图调用的webapi方法在未经授权时不返回登录页面?


它是一个MVC5应用程序,还具有用于通过javascript进行调用的WebApi控制器。


下面的两种方法


[Route("api/home/LatestProblems")]      

[HttpGet()]

public List<vmLatestProblems> LatestProblems()

{

    // Something here

}


[Route("api/home/myLatestProblems")]

[HttpGet()]

[Authorize(Roles = "Member")]

public List<vmLatestProblems> mylatestproblems()

{

   // Something there

}

通过以下角度代码调用:


angular.module('appWorship').controller('latest', 

    ['$scope', '$http', function ($scope,$http) {         

        var urlBase = baseurl + '/api/home/LatestProblems';

        $http.get(urlBase).success(function (data) {

            $scope.data = data;

        }).error(function (data) {

            console.log(data);

        });

        $http.get(baseurl + '/api/home/mylatestproblems')

          .success(function (data) {

            $scope.data2 = data;

        }).error(function (data) {

            console.log(data);

        });  

    }]

);

因此,我尚未登录,第一个方法成功返回了数据。第二种方法返回(在成功函数中)包含登录页面等效项的数据。例如,如果您请求带有[Authorize]标记的控制器操作并且尚未登录,则在mvc中会得到什么。


我希望它返回未经授权的401,以便我可以根据用户是否登录为用户显示不同的数据。理想情况下,如果用户已登录,则我希望能够访问Controller的User属性,以便我可以返回特定于该Member的数据。


更新:由于以下任何建议似乎都不再起作用(对Identity或WebAPI的更改),我在github上创建了一个原始示例,该示例可以说明问题。


婷婷同学_
浏览 1537回答 3
3回答

拉风的咖菲猫

如果要在asp.net MVC网站中添加asp.net WebApi,则可能要对某些请求进行未经授权的响应。但是随后ASP.NET基础结构开始起作用,当您尝试将响应状态代码设置为HttpStatusCode时。未经授权,您将获得302重定向到登录页面。如果您在此处使用asp.net身份和基于owin的身份验证,则可以使用以下代码来解决该问题:public void ConfigureAuth(IAppBuilder app){&nbsp; &nbsp; app.UseCookieAuthentication(new CookieAuthenticationOptions&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,&nbsp; &nbsp; &nbsp; &nbsp; LoginPath = new PathString("/Account/Login"),&nbsp; &nbsp; &nbsp; &nbsp; Provider = new CookieAuthenticationProvider()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OnApplyRedirect = ctx =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!IsApiRequest(ctx.Request))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.Response.Redirect(ctx.RedirectUri);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);}private static bool IsApiRequest(IOwinRequest request){&nbsp; &nbsp; string apiPath = VirtualPathUtility.ToAbsolute("~/api/");&nbsp; &nbsp; return request.Uri.LocalPath.StartsWith(apiPath);}
打开App,查看更多内容
随时随地看视频慕课网APP