Angular POST 到网络 API

Angular POST to Web API

因此,我正在尝试使用我现有的网站 API 创建一个注册页面。 在 AccountController 上有几个 post 方法,但除了 2 个之外,我已经将它们全部注释掉了。它们看起来像这样:

/// <summary>
/// Handles all account related functions.
/// </summary>
[Authorize]
[RoutePrefix("Account")]
public class AccountController : ApiController
{
    private const string LocalLoginProvider = "Local";

    private readonly IUnitOfWork unitOfWork;
    private readonly UserService<User> service;
    private readonly UserLoginService userLoginService;
    private readonly RoleService<User> roleService;
    private readonly ISecureDataFormat<AuthenticationTicket> accessTokenFormat;

    /// <summary>
    /// Parameterless Constructor which references the startup config auth options access token format.
    /// </summary>
    public AccountController()
        : this(StartupConfig.OAuthOptions.AccessTokenFormat)
    {
    }

    /// <summary>
    /// Constructor with the access token format parameter.
    /// </summary>
    /// <param name="accessTokenFormat">The parameter for specifying the access token format.</param>
    public AccountController(ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
    {
        this.unitOfWork = new UnitOfWork<DatabaseContext>();
        this.service = new UserService<User>(this.unitOfWork, false, true);
        this.userLoginService = new UserLoginService(this.unitOfWork);
        this.roleService = new RoleService<User>(this.unitOfWork);
        this.accessTokenFormat = accessTokenFormat;
    }

    // POST api/account/register
    /// <summary>
    /// Registers a new user with the system.
    /// </summary>
    /// <param name="model">The model representing the user.</param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    [Route("Register")]
    [ResponseType(typeof(r3plica.Identity.IdentityResult))]
    public async Task<IHttpActionResult> Register(RegisterBindingViewModel model)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        var user = new User
        {
            UserName = model.Email,
            Email = model.Email
        };

        var result = await service.CreateAsync(user, model.Password);
        var errorResult = GetErrorResult(result);

        if (errorResult != null)
            return errorResult;

        await this.unitOfWork.SaveChangesAsync();

        return Ok(user.Id);
    }

    // POST api/account/logout
    /// <summary>
    /// Logs the current user out.
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [Route("Logout")]
    public IHttpActionResult Logout()
    {
        Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);

        return Ok();
    }
}

我的 angular 控制器看起来像这样:

.controller('RegisterController', ['$state', 'Api', function ($state, api) {
    var self = this;

    self.model = {
        email: '',
        password: '',
        confirmPassword: ''
    };

    self.register = function () {
        api.post('account/register', self.model).then(function (response) {
            console.log(response);
        }, function (error) {
            alert('error!');
        });
    };
}]);

如果我在我的 AccountController 中注释掉 Logout 函数,然后尝试注册,它注册正常并且所有字段都已填充并正确。 如果我取消注释 Logout 并发送相同的表单,我会得到一个错误:

Multiple actions were found that match the request:

Register on type AccountController

Logout on type AccountController

如您所见,Logout 是无参数的,所以我不确定为什么会出现此错误。谁能告诉我我做错了什么?

原来你的WebApiConfig

中需要一行非常重要的代码

config.MapHttpAttributeRoutes();

没有这个,设置路由会被忽略,所以说这段代码:

[Route("Register")] 

不会被击中。因为 RegisterLogout 都装饰有 [HttpPost],这意味着它们被视为一样。