我有以下jquery代码,它成功地从相同(项目)端口号对web api进行授权调用,并使用以下jquery代码
<script>
$(document).ready(function(){
var ulEmployees = $('#ulEmployee');
var username = $('#uname').val();
var password = $('#pword').val();
username = "male";
password = "male";
$('#btn').click(function () {
$.ajax({
type: 'GET',
url: 'api/Employees',
dataType: 'json',
headers: {
'Authorization': 'Basic' + btoa(username + ':' + password)
},
success: function (data)
{
ulEmployees.empty();
$.each(data, function (index, val) {
var fullName = val.FirstName + ''+val.gender + '' + val.LastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
},
});
});
$('#btnclear').click(function(){
ulEmployees.empty();
});
});
});
如果我从不同的项目提出请求它将无效
我在请求
中使用以下值作为url参数url:&#39; http://localhost:53099/api/Employees&#39;
我在web api中使用了授权代码
<pre>
[BasicAuthentication]
public HttpResponseMessage Get(string gender = "ALL")
{
string username = Thread.CurrentPrincipal.Identity.Name;
// string username = "male";
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
//int id = 4;
//var entity = entities.Employees.FirstOrDefault(e => e.ID == id);
//return Request.CreateResponse(HttpStatusCode.OK, entity);
switch (username.ToLower())
{
case "male":
return Request.CreateResponse(HttpStatusCode.OK,
entities.Employees.Where(e => e.Gender.ToLower() == "male").ToList());
case "female":
return Request.CreateResponse(HttpStatusCode.OK,
entities.Employees.Where(e => e.Gender.ToLower() == "female").ToList());
default:
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
答案 0 :(得分:0)
运行webapi时,它会在某个特定端口号上托管在本地IIS Express上。您将无法从其他端口号访问此API,因为它未托管在该端口上。