Search code examples
c#jsonauthorizationhttprequestx-www-form-urlencoded

Getting content-type from HttpActionContext


I am trying to do an authorization of an endpoint based on a value passed in the body request. For example, a siteID is passed in the body of the request & I want to do authorization based on if the user has the appropriate permissions to that site.

I have this working if the body request is passed as json, but not if it's form urlencoded. And I can't figure out how to find that out beforehand. Here is a snippet of my code that works with json data, but fails if body request is urlencoded.

 public override void OnAuthorization(HttpActionContext actionContext)
    {
        var request = actionContext.Request;

                try
                {
                    var content = actionContext.Request.Content.ReadAsStringAsync().Result;
                    var jsonResult = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(content);
                    _siteId = jsonResult["siteID"].ToString();
                    actionContext.Response = UserWorker.UserValidation(_siteId, request) as HttpResponseMessage;
                }
                catch (Exception e)
                {
                    actionContext.Response = request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
                }

Solution

  • You can get the content-type from the Request object. Try this:

     public override void OnAuthorization(HttpActionContext actionContext)
        {
            var request = actionContext.Request;
    
            try
            {
                var content = actionContext.Request.Content.ReadAsStringAsync().Result;
                var contentType = request.Content.Headers.ContentType;
                string _siteId = string.Empty;
                if (contentType.MediaType == "application/json") //JSON case:
                {
                    dynamic jsonResult = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(content);
                    _siteId = jsonResult["siteID"].ToString();
                }
                else // form urlencode case:
                {
                    _siteId = content.Split('=')[0] == "siteID" ? content.Split('=')[1] : string.Empty;
    
                }
    
                actionContext.Response = UserWorker.UserValidation(_siteId, request) as HttpResponseMessage;
            }
            catch (Exception e)
            {
                actionContext.Response = request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }
    
        }