2014-02-05 84 views
0

我把從煎茶觸摸Ajax請求我的asp.net mvc的服務:發送JSON AJAX POST請求到ASP.NET MVC錯誤

Ext.Ajax.request({ 
     url: 'http://localhost:52771/api/login', 
     method: 'post', 
        defaultHeaders : 'application/json', 
     params: { 
      post: JSON.stringify ({ 
        user: username, 
        pwd: password 
       }) 
     }, 
     success: function (response) { 

      var loginResponse = Ext.JSON.decode(response.responseText); 

      if (loginResponse === true) { 
       // The server will send a token that can be used throughout the app to confirm that the user is authenticated. 
       me.sessionToken = loginResponse.sessionToken; 
       me.signInSuccess();  //Just simulating success. 
      } else { 
       me.signInFailure(loginResponse.message); 
      } 
     }, 
     failure: function (response) { 
      me.sessionToken = null; 
      me.signInFailure('Login failed. Please try again later.'); 
     } 
    }); 

這裏是服務代碼:

Namespace SimpleSevice 
Public Class LoginController 
    Inherits ApiController 

    Private Shared list As IList(Of Login1) = New List(Of Login1)(_ 
       {New Login1() With {.user = "User", .pwd = "Password"}, _ 
       New Login1() With {.user = "User1", .pwd = "Password1"}, _ 
       New Login1() With {.user = "User2", .pwd = "Password2"} 
       } 
    ) 

    <System.Web.Mvc.AcceptVerbs("GET")> _ 
    Public Function GetLogin() As IEnumerable(Of Login1) 
     Return list 
    End Function 

    <System.Web.Mvc.HttpPost> _ 
    Public Function PostLogin(ByVal login As Login1) As Net.Http.HttpResponseMessage 
     If login.user = "John" AndAlso login.pwd = "Human" Then 
      Return Request.CreateResponse(Of Boolean)(Net.HttpStatusCode.OK, True) 
     End If 
     Return Request.CreateResponse(Of Boolean)(Net.HttpStatusCode.NotFound, False) 
    End Function 

    End Class 
End Namespace 

我得到這些錯誤:

OPTIONS http://localhost:52771/api/login?_dc=1391588046145 405 (Method Not Allowed) 

OPTIONS http://localhost:52771/api/login?_dc=1391588046145 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

XMLHttpRequest cannot load http://localhost:52771/api/login?_dc=1391588046145. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

你能幫我嗎?

回答

1

看起來您需要在Web API上啓用跨源資源共享。默認情況下,運行應用程序的Web瀏覽器將不允許您調用另一個域(不同的端口被視爲跨域)。下面是關於如何做到這一點的Web API 2的細節...

http://msdn.microsoft.com/en-us/magazine/dn532203.aspx

編輯:如果你正在使用Web API工作1 ... http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx

+0

謝謝,現在它的工作原理,但在我的服務中,登錄無效。 –