2016-08-28 150 views
1

當我發送從客戶端請求我接收302碼,並重定向到登錄,但 下一I接收:asp.net網頁API授權302代碼

控制檯日誌:XMLHttpRequest cannot load https://login.microsoftonline.com/........................ No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:' is therefore not allowed access. Error: Response with status: 0 for URL: null

ApiController:

[Authorize] 
     public string Get() 
     { } 

我想返回狀態代碼401或類似的東西。

+0

你沒有權限調用'的https://login.microsoftonline.com/...'從產地'的https://本地主機: 44315' –

+0

是的,我知道但我想回應401或數據給客戶端,不重定向 – wroe12

+0

您需要詳細說明並給出更多代碼 –

回答

1

看起來你沒有在你的API中啓用CORS,或者你使用的是cookie身份驗證,而不是基於令牌的身份驗證。

要返回401而不是302,您可以編寫一些自定義Owin中間件來檢查控制器返回的內容,並更改響應以使其適合您的需求。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace Middleware 
{ 
    using Microsoft.Owin; 

    public sealed class MyCustomMiddleware : OwinMiddleware 
    { 
     public MyCustomMiddleware(OwinMiddleware next) 
      : base(next) 
     { 
     } 

     public override async System.Threading.Tasks.Task Invoke(IOwinContext context) 
     { 

      // Code here executed before reaching the controller 
      await Next.Invoke(context); 
      // Code here executed after reaching the controller, includes the response 
      // check response here and modify it to suit your needs 
      if(context.Response.StatusCode == 302) { 
       var headers = context.Response.Headers; 
       headers.Keys.ForEach(k => headers.Remove(k)); 
       context.Response.StatusCode = 401; 
       context.Response.ContentType = string.Empty; 
       context.Response.ContentLength = null; 
       await context.Response.WriteAsync(string.Empty); 
      } 
     } 
    } 
} 

然後在startup.cs

 app.Use<Middleware.MyCustomMiddleware>(); 
+0

是的,我使用cookie認證,但MyCustomMiddleware沒有任何變化,我有t他同樣的錯誤和302. – wroe12

+0

它甚至被調用?你有沒有在其中放置一個斷點? – Darxtar

+0

是的,我使用了斷點 – wroe12