MVC Api Action & System.Web.Http.AuthorizeAttribute - How to get message parameters?

I have the following API controller:

public class TestController : ApiController
{
    [HttpPost]
    [APIAuthorizeAttribute]
    public IQueryable<Computers> ListOfComputersInFolder(Guid folderId)
    {
        return GetListOfComputersForFolder(folderId);
    } // End of ListOfComputersInFolder
} // End of TestController 

And here is my basic one APIAuthorizeAttribute.

public class APIAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var Request = System.Web.HttpContext.Current.Request;
        var folderId = Request.RequestContext.RouteData.Values["folderId"] ?? Request.Params["folderId] as string;
        if(null == folderId)
        {
            folderId = actionContext.ControllerContext.RouteData.Values["folderId"];
        }

        base.OnAuthorization(actionContext);
    }
}

The problem I am facing is that it is folderIdgetting out of null in the onAuthorize method. (I founded the collector in this code).

It seems to me that this should work, but I cannot understand. Any ideas on what I'm doing wrong, and how do I need to get the published parameter?

Edit: I tried reading the message data directly with the following:

using (StreamReader inputStream = new StreamReader(request.InputStream))
{
    output = inputStream.ReadToEnd();
}
request.InputStream.Position = 0;

Which receives me JSON-formatted message data that I could parse, but then my call never does it. In the response, I get the following exception:

  <h2>500 - Internal server error.</h2>
  <h3>There is a problem with the resource you are looking for, and it cannot be displayed.

at System.Json.JXmlToJsonValueConverter.JXMLToJsonValue(Stream jsonStream, Byte[] jsonBytes)\u000d\u000a   at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClass7.<OnReadFromStreamAsync>b__6()\u000d\u000a   at System.Net.Http.Internal.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}

EDIT: , , ApiController, System.Web.Http.AuthorizeAttribute HttpPost ( HttpGet). .

+5
4

AuthorizeAttribute AuthorizationContext, HttpActionContext , RouteData eg

public override void OnAuthorization(AuthorizationContext filterContext)
{
    var folderId = filterContext.RouteData.Values["folderId"];
    ...
}

, ApiController Http.AuthorizeAttribute (, AuthorizationContext). RouteData , .

var folderId = actionContext.Request.GetRouteData().Values["folderId"];
+7

.

, , OnAuthorization:

private static object GetValueFromActionContext(HttpActionContext actionContext, string key)
{
    var queryNameValuePairs = actionContext.Request.GetQueryNameValuePairs();

    var value = queryNameValuePairs
        .Where(pair => pair.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
        .Select(pair => pair.Value)
        .FirstOrDefault();

    var methodInfo = ((ReflectedHttpActionDescriptor) (actionContext.ActionDescriptor)).MethodInfo;
    var parameters = methodInfo.GetParameters();
    var parameterType =
        parameters.Single(p => p.Name.Equals(key, StringComparison.OrdinalIgnoreCase)).ParameterType;

    var converter = TypeDescriptor.GetConverter(parameterType);

    return converter.ConvertFromString(value);
}

:

  • , , .

  • , , , .

  • - .

, , , Guid, Boolean, String .. .

GetQueryNameValuePairs System.Net.Http.HttpRequestMessageExtensions /.

:

object folderId = GetValueFromActionContext(actionContext, "folderId");
+1

: ( )

public static string GetParameter(this RequestContext requestContext, string key)
{
    if (key == null) throw new ArgumentNullException("key");

    var lowKey = key.ToLower();

    return requestContext.RouteData.Values.ContainsKey(lowKey) &&
           requestContext.RouteData.Values[lowKey] != null
               ? requestContext.RouteData.Values[lowKey].ToString()
               : requestContext.HttpContext.Request.Params[lowKey];
}

, actionContext .

0

content application/json;charset=utf-8

API Post :

Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
Encoding encoding = Encoding.UTF8;
stream.Position = 0;
string responseData = "";

using (StreamReader reader = new StreamReader(stream, encoding))
{
    responseData = reader.ReadToEnd().ToString();
}

var dic = JsonConvert.DeserializeObject<IDictionary<string, string>>(responseData);
0
source

All Articles