上传csv文件使用ajax调用控制器mvc c#无法在uat服务器上运行

时间:2017-03-01 12:08:40

标签: c# jquery ajax csv asp.net-mvc-4

我正在尝试将.csv文件上传到我的应用程序中。代码在我的本地电脑正常工作。但是当我在我的UAT服务器上部署相同的代码时,它给了我一个与jquery相关的错误。

错误详情如下,

我的控制器代码如下,

[HttpPost]
public JsonResult UploadCustomersLead()
{
    string sMessage = "";
    bool bStatus = true;
    bool bError = false;

    System.IO.StreamWriter file = new    System.IO.StreamWriter(System.Configuration.ConfigurationManager.AppSettings["LogFile"].ToString());
    file.WriteLine("inside upload cust");

    var attachedFile = System.Web.HttpContext.Current.Request.Files["CsvDoc"];
    if (attachedFile != null && attachedFile.ContentLength > 0)
    {
        string fileName = Path.GetFileName(attachedFile.FileName);
        string path = Path.Combine(Server.MapPath(ConfigManager.GetUploadCSVFilePathForUpload), fileName);

        file.WriteLine("inside upload cust path:" + path);
        try
        {
            attachedFile.SaveAs(path);
            DataTable dt = ConvertCSVToDataTable(path); //DataTable dt = CommonFunction.ConvertCSVToDataTable(path); //Are not working because this method is in PNRMSystem.BLL/CommonBusinessLogic.cs file.

            List<string> l = new List<string>();
            if (dt.Rows.Count > 0)
            {
                MerchantMasterService.MerchantMasterClient merchantMasterClient = new MerchantMasterService.MerchantMasterClient();
                foreach (DataRow row in dt.Rows)
                {
                    MerchantMasterService.AddCustomerLeadsFromAdminRequest addCustomerLeadsFromMerchantDashboardRequest = new MerchantMasterService.AddCustomerLeadsFromAdminRequest
                    {
                        RegisteredMobileNumber = row["SellerNumber"].ToString(),         //MerchantMobileNumber;
                        CustomerMobileNumber = row["CustomerNumber"].ToString(),         //CustomerMobileNumber,
                        CustomerName = row["CustomerName"].ToString(),                   //CustomerName,
                        Address = row["Address"].ToString(),                             //Address,
                        BillAmount = Convert.ToDecimal(row["BillAmount"].ToString())     //BillAmount
                    };
                                                                                                                                                                                                         MerchantMasterService.AddCustomerLeadsFromAdminResponse addCustomerLeadsFromMerchantDashboardResponse = merchantMasterClient.AddCustomerLeadsFromAdmin(addCustomerLeadsFromMerchantDashboardRequest);
                    if  (addCustomerLeadsFromMerchantDashboardResponse.StatusCode.ToString().ToLower().Equals("failure"))
                    {
                        l.Add(row["CustomerNumber"].ToString());
                    }
                }
            }
            dt.Dispose();
            ModelState.Clear();
            var Number = l.Count > 0 ? string.Join(",", l) : "None";
            sMessage = "Total Records : " + dt.Rows.Count + "</br>" + "Total Success : " + (dt.Rows.Count - l.Count) + "<br/>" + "Total failure : " + l.Count + "<br/>" + "Total failure Number : " + Number;
        }
        catch (Exception ex)
        {
             ModelState.AddModelError("File", ex.Message.ToString());
             CreateLog.Error(this.GetType(), "Error occured on UploadCustomersLead action in Customers controller in merchant dashboard.", ex);
             bError = true;
             sMessage = "An error occured. Please try again.";
             throw;
        }
        finally
        {
             if (System.IO.File.Exists(path))
             {
                 System.IO.File.Delete(path);
             }
             file.Close();
        }
    }
    else
    {
        ModelState.AddModelError("File", "Please Select Your file");
    }
    return Json(new { Message = sMessage, Status = bStatus, Error = bError }, JsonRequestBehavior.AllowGet);
}

和.cshtml文件的jquery代码如下,

$("#btnUploadCustLeads").click(function () {
                var fileExtension = ['csv'];
                if ($("#IDofTheUploader").val() == "" || $("#IDofTheUploader").val() == null || $.inArray($("#IDofTheUploader").val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                    $('#statusBoxUploadCustLeads').removeClass('alert-danger').addClass('alert-success').show(500, function () {
                        $('#statusMessageUploadCustLeads').html("Kindly select the .csv file to be uploaded.");
                    });
                }
                else {
                    $('#imgLoadingAddCustomer').removeAttr("style");
                    var fileUpload = document.getElementById("IDofTheUploader");
                    if (fileUpload.value != null) {
                        var uploadFile = new FormData();
                        var files = $("#IDofTheUploader").get(0).files;
                        // Add the uploaded file content to the form data collection
                        if (files.length > 0) {
                            uploadFile.append("CsvDoc", files[0]);
                            $.ajax({
                                url: "/Customers/UploadCustomersLead",
                                contentType: false,
                                processData: false,
                                data: uploadFile,
                                type: 'POST',
                                success: function (data) {
                                    $('#statusBoxUploadCustLeads').removeClass('alert-danger').addClass('alert-success').show(500, function () {
                                        $('#statusMessageUploadCustLeads').html(data.Message);
                                        ClearUploadCustLeadsControls();
                                    });
                                },
                                complete: function () {
                                    $('#imgLoadingAddCustomer').css("display", "none");
                                }
                            });
                        }
                    }
                    else {
                        $('#statusBoxUploadCustLeads').removeClass('alert-danger').addClass('alert-success').show(500, function () {
                            $('#statusMessageUploadCustLeads').html("File to be uploaded can not be bank.");
                        });
                    }
                }
            });

2 个答案:

答案 0 :(得分:0)

我会发表评论,但我没有足够的代表。

尝试检查UAT服务器的路由配置。当我在控制器上有多个GET方法时,我遇到了类似的错误 - 我需要指定一个路径,该路由将方法名称作为参数使用类似的东西:

routes.MapHttpRoute(
            name: "CallMethodByName",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

如果这条配置不在UAT服务器中,它将无法正确处理请求并返回404错误。

编辑:新配置应低于旧配置(更具体的说明应该更晚)。这应该适用于post以及get方法。您的测试配置与UAT配置相比如何?

答案 1 :(得分:0)

@princeofmince,我已尝试使用

进行路由配置
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapHttpRoute(
name: "CallMethodByName",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);   
在服务器上的routeconfig.cs文件中

但是没有工作,我的操作方法是 [httppost] 方法而不是 [httpget]