0

我正在尝试根据正文请求中传递的值对端点进行授权。例如,在请求的正文中传递了一个 siteID,我想根据用户是否对该站点具有适当的权限来进行授权。

如果正文请求作为 json 传递,我有这个工作,但如果它是 urlencoded 形式则没有。而且我不知道如何事先找到它。这是我的代码片段,适用于 json 数据,但如果正文请求是 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);
                }
4

1 回答 1

1

您可以从 Request 对象中获取内容类型。尝试这个:

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

    }
于 2021-02-18T20:49:17.310 回答