【发布时间】:2017-03-10 16:05:41
【问题描述】:
为了理解这一点,我使用来自asp.net 的示例应用程序 当我运行它并使用他们拥有的示例页面时,一切都很好。
然后我创建一个启用了 mvc 脚手架的新空 asp.net 项目,并重新创建具有 2 个不同层的场景。我可以使用此表单操作进行注册:
<form method="post" action="https://localhost:44305/api/Account/Register">
<h3>Register</h3>
<div class="form-group">
<label>Email</label>
@Html.TextBoxFor(m => m.Email, new { id = "txtUserName", @class = "form-control" })
</div>
<div class="form-group">
<label>Password</label>
@Html.PasswordFor(m => m.Password, new { id = "txtPassword", @class = "form-control" })
</div>
<div class="form-group">
<label>Confirm Password</label>
@Html.PasswordFor(m => m.ConfirmPassword, new { id = "txtConfirmPassword", @class = "form-control" })
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Register</button>
</div>
</form>
但是当我尝试登录时,它会重定向到我输入的用户名/密码作为查询字符串的同一页面:(http://localhost:57972/?Email=username&Password=password)
<div class="form-group">
<label>Email</label>
@Html.TextBoxFor(m => m.Email, new { id = "txtloginUserName", @class = "form-control" })
</div>
<div class="form-group">
<label>Password</label>
@Html.PasswordFor(m => m.Password, new { id = "txtloginPassword", @class = "form-control" })
</div>
<div class="form-group">
<button id="btnLogin" class="btn btn-default">Log In</button>
</div>
<script>
var token = "";
$('#btnLogin').click(function () {
var username = $('#txtloginUserName').val();
var password = $('#txtloginPassword').val();
$.ajax({
type: 'POST',
url: 'http://localhost:26812/Token',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
grant_type: 'password',
username: username,
password: password
},
success: function (data) {
token = data.access_token;
}
})
});
</script>
** 更新
我意识到我必须调用 /Token 的完整 url,现在当我登录并查看网络数据包时,它会以 200 OK 状态码响应,但随后会在控制台中弹出一个错误: “请求的资源上没有 'Access-Control-Allow-Origin' 标头。因此,不允许访问 Origin 'http://localhost:57972'。”
我已将 config.EnableCors() 添加到我的 webapiconfig 中,并在我的 apicontroller 上添加了注释以允许所有用于测试目的:
[EnableCors(origins: "*", headers:"*", methods:"*")]
【问题讨论】:
-
确认是来自飞行前
OPTIONS请求的No 'Access-Control-Allow-Origin'错误,对吧? -
奇怪的是 POST 请求本身返回 OK,然后它会抛出该错误,但在日志中我只看到一个请求,它是 POST。
-
有很多关于
Access-Control-Allow-Origin与 MVC API 的问题,我在整理它们时遇到了麻烦。选项中没有这个很好。尝试将ajax请求的datatype设置为dataType: "jsonp",看看是否还有这个问题。 -
当我将其更改为 jsonp 时,它会将请求转换为 GET 并引发不同的错误?我安装了 PostMan 并在运行 IIS express 的情况下尝试在那里发送相同的请求,但由于 unsupported_grant_type 失败。所以这让我觉得我的电话很好,但服务器需要改变一些东西才能接受它?它实际上是添加了 CORS 的默认 microsoft web api 自动生成的项目。
-
对不起,我应该提到
jsonp仅适用于跨域POST。不支持的授权类型是令牌发布错误。确保您的信誉在Content-Type: application/x-www-form-urlencoded; charset=UTF-8的帖子正文中。
标签: asp.net asp.net-mvc asp.net-web-api oauth-2.0 asp.net-identity