oli*_*lif 57 .net authorization asp.net-mvc-4 asp.net-web-api
是否可以通过HttpActionContext对象访问post或get参数?
我有一组传感器可以将数据记录到提供REST API的Web服务器上.我想通过让传感器在数据中包含其硬件ID然后在数据库中查找以查看id是否存在来介绍某种身份验证/授权.由于API提供了许多web api操作方法,我最好使用自定义授权属性
public class ApiAuthorizationFilter : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
如何从actionContext访问post/get数据?
编辑:POST的示例
POST /Api/api/ActionMethod/ HTTP/1.1\r\n
Content-Type: application/json\r\n
Host: localhost\r\n
Accept: */*\r\n
Content-Length:52\r\n
\r\n
{"Id": '121a222bc', "Time": '2012-02-02 12:00:00'}\r\n
Run Code Online (Sandbox Code Playgroud)
祝你今天愉快!
Mar*_*nes 62
由于其性质,AuthoriseAttribute看起来像在模型绑定器和参数绑定运行之前在管道中调用.当您访问Request.Content并从中读取时也遇到问题...这只能执行一次,如果您要在auth属性中尝试它,您可能会破坏mediaTypeFormater ...
在WebAPI中,请求主体(HttpContent)可以是只读,无限,非缓冲,不可重绕的流.
更新 有不同的方法来指定执行上下文... http://msdn.microsoft.com/en-us/library/system.web.http.filters.filterscope(v=vs.108).aspx.AuthoriseAttribute是"全局",因此访问动作信息的时间过早.
如果您想要访问模型和参数,您可以稍微改变您的方法并使用OnActionExecuting过滤器("Action"过滤器范围),并根据您的验证抛出401或403.
此过滤器稍后在执行过程中调用,因此您可以完全访问绑定数据.
非常简单的例子如下:
public class ApiAuthorizationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
Foo model = (Foo)actionContext.ActionArguments["model"];
string param1 = (string)actionContext.ActionArguments["param1"];
int param2 = (int)actionContext.ActionArguments["param2"];
if (model.Id != "1")
throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);
base.OnActionExecuting(actionContext);
}
}
Run Code Online (Sandbox Code Playgroud)
示例控制器:
public class Foo
{
public string Id { get; set; }
public DateTime Time { get; set; }
}
public class FoosController : ApiController
{
// PUT api/foos/5
[ApiAuthorizationFilter]
public Foo Put(int id, Foo model, [FromUri]string param1 = null, int? param2 = null)
{
return model;
}
}
Run Code Online (Sandbox Code Playgroud)
其他答案说的是......他们是对的,如果你可以访问URL上的所有内容,可以通过请求获取内容; 但是,我认为模型和请求内容应该保持不变:
var queryStringCollection = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
//example for param1
string param1 = queryStringCollection["param1"];
//example for param2
int param2 = int.Parse(queryStringCollection["param2"]);
//Example of getting the ID from the URL
var id = actionContext.Request.RequestUri.Segments.LastOrDefault();
Run Code Online (Sandbox Code Playgroud)
sim*_*olo 25
我在调用类似的东西时访问了上下文路由数据以从自定义AuthorizeAttribute中获取参数/api/client/123/users:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var clientId = Convert.ToInt32(actionContext.ControllerContext.RouteData.Values["clientid"]);
// Check if user can access the client account.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59371 次 |
| 最近记录: |