第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

未經(jīng)授權(quán)的webapi調(diào)用返回登錄頁面而不是401

未經(jīng)授權(quán)的webapi調(diào)用返回登錄頁面而不是401

婷婷同學(xué)_ 2019-10-06 13:03:26
如何配置我的mvc / webapi項目,以使從剃刀視圖調(diào)用的webapi方法在未經(jīng)授權(quán)時不返回登錄頁面?它是一個MVC5應(yīng)用程序,還具有用于通過javascript進(jìn)行調(diào)用的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}通過以下角度代碼調(diào)用: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);        });      }]);因此,我尚未登錄,第一個方法成功返回了數(shù)據(jù)。第二種方法返回(在成功函數(shù)中)包含登錄頁面等效項的數(shù)據(jù)。例如,如果您請求帶有[Authorize]標(biāo)記的控制器操作并且尚未登錄,則在mvc中會得到什么。我希望它返回未經(jīng)授權(quán)的401,以便我可以根據(jù)用戶是否登錄為用戶顯示不同的數(shù)據(jù)。理想情況下,如果用戶已登錄,則我希望能夠訪問Controller的User屬性,以便我可以返回特定于該Member的數(shù)據(jù)。更新:由于以下任何建議似乎都不再起作用(對Identity或WebAPI的更改),我在github上創(chuàng)建了一個原始示例,該示例可以說明問題。
查看完整描述

3 回答

?
拉風(fēng)的咖菲貓

TA貢獻(xiàn)1995條經(jīng)驗 獲得超2個贊

如果要在asp.net MVC網(wǎng)站中添加asp.net WebApi,則可能要對某些請求進(jìn)行未經(jīng)授權(quán)的響應(yīng)。但是隨后ASP.NET基礎(chǔ)結(jié)構(gòu)開始起作用,當(dāng)您嘗試將響應(yīng)狀態(tài)代碼設(shè)置為HttpStatusCode時。未經(jīng)授權(quán),您將獲得302重定向到登錄頁面。


如果您在此處使用asp.net身份和基于owin的身份驗證,則可以使用以下代碼來解決該問題:


public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(new CookieAuthenticationOptions

    {

        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

        LoginPath = new PathString("/Account/Login"),

        Provider = new CookieAuthenticationProvider()

        {

            OnApplyRedirect = ctx =>

            {

                if (!IsApiRequest(ctx.Request))

                {

                    ctx.Response.Redirect(ctx.RedirectUri);

                }

            }

        }

    });


    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

}



private static bool IsApiRequest(IOwinRequest request)

{

    string apiPath = VirtualPathUtility.ToAbsolute("~/api/");

    return request.Uri.LocalPath.StartsWith(apiPath);

}


查看完整回答
反對 回復(fù) 2019-10-06
  • 3 回答
  • 0 關(guān)注
  • 1618 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號