Web API日志记录请求,响应但跳过文件上载

时间:2016-09-14 23:03:05

标签: c# asp.net-web-api

我的登录程序存在问题。

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {

        WebApiLogin log = new WebApiLogin();
        string clientToken = "";
        string clientAddress = "";
        string requestUri = "";
        string requestBody = "";
        string responseBody = "";
        HttpResponseMessage result = null;

        try
        {

            clientToken = request.Headers.GetValues("Token").FirstOrDefault();
            requestUri = request.RequestUri.AbsoluteUri;
            clientAddress = HttpContext.Current.Request.UserHostAddress;

            // log request body
            requestBody = await request.Content.ReadAsStringAsync();

            // let other handlers process the request
            result = await base.SendAsync(request, cancellationToken);

            if (result.Content != null)
            {
                // once response body is ready, log it
                responseBody = await result.Content.ReadAsStringAsync();
                // log full
                log.Log(clientToken, clientAddress, requestUri, requestBody, responseBody);
            }
            else
            {
                // log partial
                log.Log(clientToken, clientAddress, requestUri, requestBody);
            }

        }
        catch (Exception ex)
        {
            log.Log(clientToken, clientAddress, requestUri, requestBody, ex.Message);
        }

        return result;
    }

在请求和响应中使用json调用API时,一切正常。

但问题开始于我的日志存储库开始增长,整个过程开始延迟一点点。由于异步调用 - 我猜 - 当调用一个方法在呼叫上发送一些文件用于上传时,我收到了一个错误。在我的方法下面:

public IHttpActionResult Post()
    {

        try
        {

            string sCnn = GetClientCnnFromToken();

            if (!String.IsNullOrEmpty(sCnn))
            {

                var httpRequest = HttpContext.Current.Request;
                if (httpRequest.Files.Count > 0)
                {

                    Ecommerce.DAL.BackEnd.Configuration.System objConfig = new Ecommerce.DAL.BackEnd.Configuration.System(sCnn);

                    using (DataTable dtb = objConfig.Management("RETORNA-PARAMETRO"))
                    {

                        if (!dtb.Rows[0].IsNull("str_cnn_cdn_content") && dtb.Rows[0]["str_cnn_cdn_content"].ToString() != "")
                        {

                            //storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
                            var storageAccount = CloudStorageAccount.Parse(dtb.Rows[0]["str_cnn_cdn_content"].ToString());

                            //create client to work with blobs
                            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                            //already created container via azure management portal, set container reference
                            CloudBlobContainer container = blobClient.GetContainerReference("product");

                            foreach (string file in httpRequest.Files)
                            {
                                var postedFile = httpRequest.Files[file];

                                CloudBlockBlob blockBlob = container.GetBlockBlobReference(postedFile.FileName);
                                blockBlob.Properties.ContentType = "image/jpeg";
                                blockBlob.UploadFromStream(postedFile.InputStream);

                            }

                            return Ok();

                        }
                        else
                        {
                            throw new Exception("Unable to retrieve CDN configuration for this costumer. Refer to e-commerce configuration for more details.");
                        }

                    }

                }
                else
                {
                    return BadRequest("You must post images in files on request. Files Count = 0");
                }

            }
            else
            {
                throw new Exception("Invalid Token");
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

在这一行:

var httpRequest = HttpContext.Current.Request;

由于HttpContext为null,我的“Object Reference not set”错误。我想由于日志方法上的异步调用之间的延迟。

停止日志方法“空引用”错误停止。

有没有办法解决这个问题,我的意思是,记录json和文件上传?

如果没有,是否可以在涉及文件上传时跳过此日志记录?

提前致谢,

0 个答案:

没有答案