如何在离子中发布到webapi?

时间:2017-02-03 06:47:50

标签: angularjs asp.net-web-api ionic-framework

当我运行我的应用并在Chrome中发布数据时,它显示以下错误:POST http://10.10.9.169/UserService/api/account 401(未经授权)

我已经安装了cors并在webapiconfig.cs文件中启用了它,我还在global.asax文件中添加了以下内容:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    //HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

这是我的controllers.js代码:

.controller('SignUp15Ctrl', ['$scope', '$stateParams', '$location','userFactoryReg', function ($scope, $stateParams, $location, userFactoryReg) {
    $scope.userdataReg = {}
    $scope.enterloginReg = function(usern,pass1,pass2) {
        if(pass1!=pass2)
        {
            alert('Passwords do not match.');
        }
        if(pass1 == pass2)
        {
            userFactoryReg.postUser(usern,pass1,pass2).then(function(response)
            {
                if(JSON.stringify(response.data) === "null")
                {
                    alert('Error');
                }
                else
                {
                    alert('Accoiunt successfully created.');
                    $location.path('/page4');
                }
            });
        }
    }
}])

这是我的services.js代码:

.factory('userFactoryReg', ['$http', function($http) {
    var users = [];
    return {
        postUser: function(uname,passw1,passw2){
            return $http.post("http://10.10.9.169/UserService/api/account/register", {"Username" :uname, "Password" :passw1, "ConfirmPassword" :passw2} );
        }
    }
}])

这是我的webapi部分代码:

[AllowAnonymous]
public HttpResponseMessage Post([FromBody] User user)
{
    try
    {
        using (UsersDBEntities entities = new UsersDBEntities())
        {
            entities.Users.Add(user);
            entities.SaveChanges();

            var message = Request.CreateResponse(HttpStatusCode.Created, user);
            message.Headers.Location = new Uri(Request.RequestUri + user.Username.ToString());

            return message;
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

1 个答案:

答案 0 :(得分:0)

第一个问题是由于API动作没有[AllowAnonymous]而需要在全局或控制器级别使用[Authorize]进行身份验证。您必须允许未经身份验证的用户访问身份验证终结点。

第二个问题是返回HTTP 400,但这是由于User实体中的验证错误。