我已成功从web api控制器登录。但是,当我尝试从MVC控制器获取授权数据时,它会返回401未授权。这是我的web api登录控制器。
using crudaspangularjs.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
namespace crudaspangularjs.Controllers
{
[RoutePrefix("api")]
[Authorize]
public class AuthController : ApiController
{
[Route("login")]
[AllowAnonymous]
[ResponseType(typeof(AdminLoginModel))]
public IHttpActionResult Login(AdminLoginModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
CrudAspAngularjsDbEntities2 db = new CrudAspAngularjsDbEntities2();
Admin adminLoggedin = db.Admins.SingleOrDefault(x=>x.Email==model.Email && x.Password == model.Password);
if (adminLoggedin == null)
{
return BadRequest();
}
else
{
var authUser = from admin in db.Admins
where admin.Email == adminLoggedin.Email
select new AdminLoginViewModel { Email =
admin.Email, Name = admin.Name, RoleId =
admin.RoleId, RoleName = admin.RoleName };
return Ok(authUser);
}
}
}
}
这是mvc控制器。
using Rotativa;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using crudaspangularjs.Models;
namespace crudaspangularjs.Controllers
{
[Authorize]
public class UserController : Controller
{
private CrudAspAngularjsDbEntities db = null;
public UserController()
{
db = new CrudAspAngularjsDbEntities();
}
[Authorize]
public ActionResult Index()
{
var user = db.Users.ToList();
return Json(user, JsonRequestBehavior.AllowGet);
}
[Authorize]
public JsonResult Details(int id)
{
var user = db.Users.Find(id);
return Json(user, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
public JsonResult Create(User user)
{
db.Users.Add(user);
db.SaveChanges();
return Json(null);
}
[Authorize]
[HttpPost]
public JsonResult Edit(User user)
{
db.Entry(user).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return Json(null);
}
[Authorize]
[HttpPost]
public JsonResult Delete(int id)
{
var user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
return Json(null);
}
[Authorize]
public ActionResult PrintViewToPdf()
{
var report = new ActionAsPdf("Data")
{
FileName = "ReportData.pdf",
PageSize = Rotativa.Options.Size.A4
};
return report;
}
[Authorize]
public ActionResult Data()
{
// ViewBag.user = db.Users.ToList();
var user = db.Users.ToList();
return View(user);
}
}
}
但是每当我执行一个动作时,它都会返回401。寻求帮助!提前致谢
答案 0 :(得分:2)
要使用户经过身份验证,您必须执行登录操作。
您在Login
方法中执行的操作是检查凭据,但登录是您(在某些身份验证API的帮助下)将用户身份设置为(最常见)Cookie的地方,例如:
FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
答案 1 :(得分:1)
您也可以使用ASP Identity。您可以Authorize开箱即用的用户。