1

我是 ASP.NET 的新手,休息...

我只是在制作一个 web api2 我的 REST 服务器已准备就绪,客户端也已准备就绪。

API 只能由具有用户名和密码的有效用户访问。因此需要检查有效用户,所以我尝试通过以下方式访问用户:

var uri = 'http://localhost/ProductsApp/api/products/username/password';

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON(uri)
        .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
                // Add a list item for the product.
                $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
        });
});

在那个调用它访问下面的方法:

public IEnumerable<Clients> GetAllClients( string username, string password)
{

    //Here i tried to check the username and password

    HttpRequestMessage message = new HttpRequestMessage();
    message.GetClientCertificate();
    return dbContext.Clients.ToList();
}

但抛出错误。看来这不是这样的方法。请你能帮我推荐一个好的教程或解决这个问题......这将非常有帮助。

4

1 回答 1

0

可以在此处找到实现 webapi2 的默认承载身份验证的演练。

要注册用户,您需要发布到 /api/account/register。正文将包括 UserName、Password 和 ConfirmPassword 属性。

{
    'UserName': 'neil',
    'Password': 'secretPassword',
    'ConfirmPassword: 'secretPassword'
}

并添加 Content-Type: application/json 作为标题。

拥有注册用户后,您可以通过发布到 /Token 并接收用于识别用户的令牌来登录他们。您需要在这篇文章中添加以下标题:

Content-Type: application/x-www-form-urlencoded

身体看起来像:

grant_type=password&username=neil&password=secretPassword

该帖子将返回一个令牌。您需要将令牌作为标头包含在以下请求中。标题看起来像:

Authorization: bearer xxx *where xxx is the token.*
于 2014-01-24T19:58:11.537 回答