C# 在.NETMVC中禁止Ajax POST返回403#
(已经尝试了不同的解决方案,但没有任何效果) 我正在尝试执行一个JQuery POST请求,将列表和对象从区域视图保存到区域控制器,以将其保存到数据库中,并返回带有结果(错误或数据)的匿名Json对象 现在,当我在本地主机上尝试它时,它会像我预期的那样工作,但是当我使用FTP发布项目并执行该请求时,什么也没有发生,并返回403禁止访问-拒绝访问。我在general path中已经有了另一个请求,而不是在localhost上运行良好并已发布的区域中 我的主机提供商说这不是他的权限问题,所以我开始尝试一些东西,但直到现在我还不能解决它 以下是我的功能请求代码:C# 在.NETMVC中禁止Ajax POST返回403#,c#,jquery,asp.net,ajax,asp.net-mvc,C#,Jquery,Asp.net,Ajax,Asp.net Mvc,(已经尝试了不同的解决方案,但没有任何效果) 我正在尝试执行一个JQuery POST请求,将列表和对象从区域视图保存到区域控制器,以将其保存到数据库中,并返回带有结果(错误或数据)的匿名Json对象 现在,当我在本地主机上尝试它时,它会像我预期的那样工作,但是当我使用FTP发布项目并执行该请求时,什么也没有发生,并返回403禁止访问-拒绝访问。我在general path中已经有了另一个请求,而不是在localhost上运行良好并已发布的区域中 我的主机提供商说这不是他的权限问题,所以我开始尝
context.MapRoute(
"Admin_Rout",
"Admin/AdminPanel/{action}/{id}",
new { controller = "AdminPanel", action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "AdminPanel", action = "Index", id = UrlParameter.Optional }
);
功能:
$(document).ready(function () {
$.ajax({
url: "@Url.Action("GetNombre","Usuarios", new { Area = "" })",
type: "POST",
success: function (foo) {
$(".foo-class").html('Hola, ' + foo.nombre + '!');
}
});
});
$("form").submit(function (e) {
e.preventDefault();
//Initializing List
var lstContacto_Clientes = [];
$("div[id*='contacto-']").each(function () {
......
});
//Datos Cliente
var Cliente = {
......
}
$.post({
url: "@Url.Action("Crear", "Clientes")",
method: "POST",
data: {
oClienteView: Cliente,
lstContactoClientes: lstContacto_Clientes
},
success: function (result) {
.....
},
error: function (e) {
console.log('JSON Error');
console.log(e);
}
});
});
以下是我的非功能性请求:
context.MapRoute(
"Admin_Rout",
"Admin/AdminPanel/{action}/{id}",
new { controller = "AdminPanel", action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "AdminPanel", action = "Index", id = UrlParameter.Optional }
);
无函数(返回403):
$(document).ready(function () {
$.ajax({
url: "@Url.Action("GetNombre","Usuarios", new { Area = "" })",
type: "POST",
success: function (foo) {
$(".foo-class").html('Hola, ' + foo.nombre + '!');
}
});
});
$("form").submit(function (e) {
e.preventDefault();
//Initializing List
var lstContacto_Clientes = [];
$("div[id*='contacto-']").each(function () {
......
});
//Datos Cliente
var Cliente = {
......
}
$.post({
url: "@Url.Action("Crear", "Clientes")",
method: "POST",
data: {
oClienteView: Cliente,
lstContactoClientes: lstContacto_Clientes
},
success: function (result) {
.....
},
error: function (e) {
console.log('JSON Error');
console.log(e);
}
});
});
这是区域路由(这就是为什么我没有在无功能请求中指定区域):
以下是我的文件夹的分发方式:
“客户”控制器受以下过滤器的影响:
public class AutorizacionRolesAttribute : AuthorizeAttribute
{
private readonly string[] allowedroles;
public AutorizacionRolesAttribute(params string[] roles)
{
//De AutorizacionRoles(Roles="") recibe los valores de -Roles=""- y los guarda en un array de strings
this.allowedroles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool authorize = false;
//Recibe el ID del Usuario por la sesion
int? userId = (int?)httpContext.Session["SessionId"];
var token = httpContext.Session["token"];
//Chequea solamente si recibe UNICAMENTE el param "Token", ningun otro
//asi se chequea en la accion "Crear" si está habilitado
if (allowedroles[0] == "Token")
{
//Si NO esta vacio, devuevle TRUE
if(token != null)
return true;
}
//Chequea si userId es valido
if (userId > 0 && userId != null)
using (var db = new PBIEntities())
{
//Recibe el Rol del Usuario
var userRole = (from u in db.Usuarios
join r in db.Roles on u.rol equals r.ID_Rol
where u.id_usuario == userId
select new
{
r.Rol
}).FirstOrDefault();
//Chequea que el Rol del Usuario esté habilitado recorriendo allowedroles
foreach (var role in allowedroles)
{
if (role == userRole.Rol) return true;
}
}
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "Home" },
{ "action", "Index" },
{ "Area", "" }
});
}
}
编辑:(我正在表单上使用@Html.AntiForgeryToken()
[HttpPost]
公共行动结果Crear(客户的oClienteView,列表LSContactOClientes)
{
ViewBag.peticion=false;
ViewBag.error=false;
JSONRespuesta JSONresp=新的JSONRespuesta();
尝试
{
if(ModelState.IsValid)
{
使用(FOOEntities db=new FOOEntities())
{
使用(DbContextTransaction=db.Database.BeginTransaction())
{
尝试
{
.....
}
捕获(例外e)
{
transaction.Rollback();
JSONresp.error=true;
JSONresp.data=e.消息;
返回Json(JSONresp,JsonRequestBehavior.AllowGet);
}
}
}
}
JSONresp.error=false;
JSONresp.op=“validacion”;
JSONresp.data=ModelState.Values.SelectMany(e=>e.Errors);
返回Json(JSONresp,JsonRequestBehavior.AllowGet);
}
捕获(例外e)
{
JSONresp.error=true;
JSONresp.data=e.消息;
返回Json(JSONresp,JsonRequestBehavior.AllowGet);
}
}
可能缺少导致错误的内容类型属性。尝试将内容类型设置为post方法。