在自定义授权 MVC4 Web Api 中访问 post 或 get 参数 [英] Accessing post or get parameters in custom authorization MVC4 Web Api

查看:25
本文介绍了在自定义授权 MVC4 Web Api 中访问 post 或 get 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过 HttpActionContext 对象访问 post 或 get 参数?

Is it possible to access post or get parameters via the HttpActionContext object?

我有一组传感器,可以将数据记录到提供 REST api 的 Web 服务器.我想通过让传感器在数据中包含它们的硬件 ID 然后在数据库中查找该 ID 是否存在来引入某种身份验证/授权.由于 API 提供了许多 web api 操作方法,因此我最好使用自定义授权属性

I have a set of sensors that loggs data to a web server that provides a REST api. I would like to introduce some sort of authentication/authorization by letting the sensors include their hardware id in the data and then make a lookup in a database to see if the id exists or not. Since the API provides many web api action methods I would ideally like to use a custom authorization attribute

public class ApiAuthorizationFilter : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        return false;
    }
}

如何从 actionContext 访问 post/get 数据?

How can I access the post/get data from the actionContext?

POST 示例

POST /Api/api/ActionMethod/ HTTP/1.1

Content-Type: application/json

Host: localhost

Accept: */*

Content-Length:52



{"Id": '121a222bc', "Time": '2012-02-02 12:00:00'}

祝您有美好的一天!

推荐答案

由于其性质,AuthoriseAttribute 看起来像是在模型绑定器和参数绑定运行之前在管道中调用.当您访问 Request.Content 并从中读取时,您也会遇到问题......这只能是 完成一次 并且如果您打算在您的 auth 属性中尝试它,您可能会破坏 mediaTypeFormater...

Due to its nature the AuthoriseAttribute looks like it is called in the pipeline before the model binders and parameter bindings have run. You also run into issues when you access the Request.Content and read from it... this can only be done once and if you are going to try it in your auth attribute you may break the mediaTypeFormater...

在 WebAPI 中,请求主体(一个 HttpContent)可能是一个只读的、无限的、非缓冲的、不可重绕的流.

in WebAPI, the request body (an HttpContent) may be a read-only, infinite, non-buffered, non-rewindable stream.

更新有多种指定执行上下文的方法... http://msdn.microsoft.com/en-us/library/system.web.http.filters.filterscope(v=vs.108).aspx.AuthoriseAttribute 是全局",因此访问操作信息为时过早.

Update There are different ways of specifying the execution context... http://msdn.microsoft.com/en-us/library/system.web.http.filters.filterscope(v=vs.108).aspx. The AuthoriseAttribute is "Global" and therefore it is hit too early to access the action information.

如果您想要访问模型和参数,您可以稍微更改您的方法并使用 OnActionExecuting 过滤器(Action"过滤器范围),并根据您的验证抛出 401 或 403.

Given you want access to the model and parameters you can change your approach slightly and use an OnActionExecuting filter ("Action" filter scope) instead and throw a 401 or 403 based on your validation.

此过滤器在执行过程的稍后调用,因此您可以完全访问绑定数据.

This filter is called later in the execution process and you therefore have full access to the bound data.

下面非常简单的例子:

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);
    }
}

示例控制器:

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;
    }
}

其他答案所说的......他们是对的,如果您可以在 URL 上访问您需要的所有内容,请通过请求获取内容;但是,我认为模型和请求内容应该单独保留:

What the other answers were saying.... they are right you can, if you can access all you need on the URL, get at stuff via the request; however, I think the model and the request content should be left alone:

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();

这篇关于在自定义授权 MVC4 Web Api 中访问 post 或 get 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆