Angularjs 此请求的授权已被拒绝。webapi与js

Angularjs 此请求的授权已被拒绝。webapi与js,angularjs,asp.net-web-api2,unauthorized,Angularjs,Asp.net Web Api2,Unauthorized,这是我的WEB API控制器 using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.H

这是我的WEB API控制器

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using ShoppingCartAPINAngularJS.Models;
using System.Web.Http.Cors;

namespace ShoppingCartAPINAngularJS.Controllers
{
[Authorize]
public class CategoriesController : ApiController
{
    private ShoppingCartEntities db = new ShoppingCartEntities();

    // GET: api/Categories
    public IQueryable<Category> GetCategories()
    {
        return db.Categories;
    }

    // GET: api/Categories/5
    [ResponseType(typeof(Category))]
    public IHttpActionResult GetCategory(int id)
    {
        Category category = db.Categories.Find(id);
        if (category == null)
        {
            return NotFound();
        }

        return Ok(category);
    }

    // PUT: api/Categories/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutCategory(int id, Category category)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != category.CategoryID)
        {
            return BadRequest();
        }

        db.Entry(category).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CategoryExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Categories
    [ResponseType(typeof(Category))]
    public IHttpActionResult PostCategory(Category category)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Categories.Add(category);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = category.CategoryID }, category);
    }

    // DELETE: api/Categories/5
    [ResponseType(typeof(Category))]
    public IHttpActionResult DeleteCategory(int id)
    {
        Category category = db.Categories.Find(id);
        if (category == null)
        {
            return NotFound();
        }

        db.Categories.Remove(category);
        db.SaveChanges();

        return Ok(category);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool CategoryExists(int id)
    {
        return db.Categories.Count(e => e.CategoryID == id) > 0;
    }
}
}
我正在使用这个angular js controller.js

(function () {
'use strict';

app.controller('categoryController', ['$http', '$location', 'authService', 'ngWEBAPISettings', categoryController]);

////categoryController.$inject = ['$location']; 

function categoryController($http, $location, authService, ngWEBAPISettings) {
    /* jshint validthis:true */

    //Creating headers for sending the authentication token along with the system.
    var authheaders = {};
    authheaders.Authorization = 'Bearer ' + authService.getToken();

    //ForDate
    var d = new Date();

    var vm = this;
    vm.title = 'Category';
    ////debugger;

    ////Vadiable for Grid
    vm.Category = [];

    ////Vadiable for Adding
    vm.addCategory = {
        categoryID: 0,
        categoryName:"",
        CreatedOn:d.getDate(),
        UpdatedOn:d.getDate()
    };
////Vadiable for Editing
vm.editCategory = {};

vm.getCategory = function () {
    ////debugger;


    //For Grid
    $http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Categories", { headers: authheaders })
    .then(function (respose) {
        //success
        ////debugger;
        angular.copy(respose.data, vm.Category);
        ////debugger;
        //var i = 2;
        ////debugger;
    }, function (response) {
        //failure
        ////debugger;
    }).finally(function () {
        ////debugger;
        //finally
    }
    );
}

vm.add = function ()
{
    ////authheaders.Content-Type="application/x-www-form-urlencoded";
    debugger;

    $http.post(ngWEBAPISettings.apiServiceBaseUri + "api/Categories", vm.addCategory, { header: authheaders })
    .then(function (repose) {
        ////success
        debugger;

    }, function (response) {
        ////failure
        debugger;
    }).finally(function () {
        vm.addCategory = {};
    });
}

vm.edit = function (id) {
    ///debugger;
    alert(id);
    $('#btnSubmit').val('Update');
}
vm.delete = function (id) {
    ////debugger;
    alert(id);
}


activate();
function activate() { vm.getCategory(); }

}
})();
这是html文件

(函数(){
"严格使用",;
app.controller('categoryController'、['$http'、'$location'、'authService'、'ngWEBAPISettings',categoryController]);
////categoryController.$inject=['$location'];
函数类别控制器($http、$location、authService、NGWebAPI设置){
/*这是真的*/
//创建用于随系统发送身份验证令牌的标头。
var authheaders={};
authheaders.Authorization='Bearer'+authService.getToken();
//福特
var d=新日期();
var vm=这个;
vm.title='Category';
////调试器;
////栅极真空发生器
vm.Category=[];
////用于添加的变量
vm.addCategory={
类别ID:0,
类别名称:“”,
CreatedOn:d.getDate(),
更新时间:d.getDate()
};
////编辑用瓦迪亚布尔
vm.editCategory={};
vm.getCategory=函数(){
////调试器;
//用于网格
$http.get(ngWEBAPISettings.apiServiceBaseUri+“api/Categories”,{headers:authheaders})
.然后(功能(响应){
//成功
////调试器;
角度复制(respose.data,vm.Category);
////调试器;
//var i=2;
////调试器;
},功能(回应){
//失败
////调试器;
}).最后(函数(){
////调试器;
//最后
}
);
}
vm.add=函数()
{
////authheaders.Content Type=“application/x-www-form-urlencoded”;
调试器;
$http.post(ngWEBAPISettings.apiServiceBaseUri+“api/Categories”,vm.addCategory,{header:authheaders})
.然后(功能(休息){
////成功
调试器;
},功能(回应){
////失败
调试器;
}).最后(函数(){
vm.addCategory={};
});
}
vm.edit=函数(id){
///调试器;
警报(id);
$('btnSubmit').val('Update');
}
vm.delete=函数(id){
////调试器;
警报(id);
}
激活();
函数activate(){vm.getCategory();}
}
})();
{{vm.title}
&时代;
添加类别
类别名称
接近
添加
类别名称
创建于
{{cat.categoryName}
{{cat.createdOn}日期:'dd-MMM-yyyy'}
函数openAddModal(){
$('#addModal').modal('show');
$('btnSubmit').val('Add');
}

只是一个提示,可以是CORS吗?您是如何配置WebApi的授权的?请在启动时查看您的配置请检查屏幕截图我是否做错了大部分看起来都不错。确保您的
'Bearer'+authService.getToken()设置正确。我看不到任何屏幕标题中提供的标题值。是的,我正在控制器级别var authheaders={};authheaders.Authorization='Bearer'+authService.getToken();
(function () {
'use strict';

app.controller('categoryController', ['$http', '$location', 'authService', 'ngWEBAPISettings', categoryController]);

////categoryController.$inject = ['$location']; 

function categoryController($http, $location, authService, ngWEBAPISettings) {
    /* jshint validthis:true */

    //Creating headers for sending the authentication token along with the system.
    var authheaders = {};
    authheaders.Authorization = 'Bearer ' + authService.getToken();

    //ForDate
    var d = new Date();

    var vm = this;
    vm.title = 'Category';
    ////debugger;

    ////Vadiable for Grid
    vm.Category = [];

    ////Vadiable for Adding
    vm.addCategory = {
        categoryID: 0,
        categoryName:"",
        CreatedOn:d.getDate(),
        UpdatedOn:d.getDate()
    };
////Vadiable for Editing
vm.editCategory = {};

vm.getCategory = function () {
    ////debugger;


    //For Grid
    $http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Categories", { headers: authheaders })
    .then(function (respose) {
        //success
        ////debugger;
        angular.copy(respose.data, vm.Category);
        ////debugger;
        //var i = 2;
        ////debugger;
    }, function (response) {
        //failure
        ////debugger;
    }).finally(function () {
        ////debugger;
        //finally
    }
    );
}

vm.add = function ()
{
    ////authheaders.Content-Type="application/x-www-form-urlencoded";
    debugger;

    $http.post(ngWEBAPISettings.apiServiceBaseUri + "api/Categories", vm.addCategory, { header: authheaders })
    .then(function (repose) {
        ////success
        debugger;

    }, function (response) {
        ////failure
        debugger;
    }).finally(function () {
        vm.addCategory = {};
    });
}

vm.edit = function (id) {
    ///debugger;
    alert(id);
    $('#btnSubmit').val('Update');
}
vm.delete = function (id) {
    ////debugger;
    alert(id);
}


activate();
function activate() { vm.getCategory(); }

}
})();