0

I have these web API methods:

[System.Web.Http.RoutePrefix("api/PurchaseOrder")]
public class PurchaseOrderController : ApiController
{
    private static ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    [System.Web.Http.Route("PagingCriticalPart")]
    [System.Web.Http.HttpPost]
    public JsonResult PagingCriticalPart([FromBody] Helper.DataTablesBase model)
    {
        logger.Info("PagingCriticalPart");
        JsonResult jsonResult = new JsonResult();
        try
        {
            if (model == null) { logger.Info("model is null."); }

            int filteredResultsCount;
            int totalResultsCount;
            var res = BLL.PurchaseOrderHandler.PagingCriticalPart(model, out filteredResultsCount, out totalResultsCount);

            var result = new List<Models.T_CT2_CriticalPart>(res.Count);
            foreach (var s in res)
            {
                // simple remapping adding extra info to found dataset
                result.Add(new Models.T_CT2_CriticalPart
                {
                    active = s.active,
                    createBy = s.createBy,
                    createdDate = s.createdDate,
                    id = s.id,
                    modifiedBy = s.modifiedBy,
                    modifiedDate = s.modifiedDate,
                    partDescription = s.partDescription,
                    partNumber = s.partNumber
                });
            };

            jsonResult.Data = new
            {
                draw = model.draw,
                recordsTotal = totalResultsCount,
                recordsFiltered = filteredResultsCount,
                data = result
            };
            return jsonResult;
        }
        catch (Exception exception)
        {
            logger.Error("PagingCriticalPart", exception);
            string exceptionMessage = ((string.IsNullOrEmpty(exception.Message)) ? "" : Environment.NewLine + Environment.NewLine + exception.Message);
            string innerExceptionMessage = ((exception.InnerException == null) ? "" : ((string.IsNullOrEmpty(exception.InnerException.Message)) ? "" : Environment.NewLine + Environment.NewLine + exception.InnerException.Message));
            jsonResult.Data = new
            {
                draw = model.draw,
                recordsTotal = 0,
                recordsFiltered = 0,
                data = new { },
                error = exception.Message
            };
            return jsonResult;
        }
    }

    [System.Web.Http.Route("UploadRawMaterialData")]
    [System.Web.Http.HttpPost]
    public JsonResult UploadRawMaterialData(string rawMaterialSupplierData)
    {
        JsonResult jsonResult = new JsonResult();
        jsonResult.Data = new
        {
            uploadSuccess = true
        };
        return jsonResult;
    }
}

When use ajax to call PagingCriticalPart, no issue.

"ajax": {
    url: 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/PagingCriticalPart',
    type: 'POST',
    contentType: "application/json",
    data: function (data) {
        //debugger;
        var model = {
            draw: data.draw,
            start: data.start,
            length: data.length,
            columns: data.columns,
            search: data.search,
            order: data.order
        };
        return JSON.stringify(model);
    },
    failure: function (result) {
        debugger;
        alert("Error occurred while trying to get data from server: " + result.sEcho);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        debugger;
        alert("Error occurred while trying to get data from server!");
    },
    dataSrc: function (json) {
        //debugger;
        for (key in json.Data) { json[key] = json.Data[key]; }
        delete json['Data'];
        return json.data;
    }
}

But when call UploadRawMaterialData from c#, it get error: 404 not found.

var data = Newtonsoft.Json.JsonConvert.SerializeObject(rawMaterialVendorUploads);
string apiURL = @"http://localhost/ControlTower2WebAPI/api/PurchaseOrder/UploadRawMaterialData";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.UseDefaultCredentials = true;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
    requestWriter.Write(data);
}

try
{
    WebResponse webResponse = request.GetResponse();
    using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
    using (StreamReader responseReader = new StreamReader(webStream))
    {
        string response = responseReader.ReadToEnd();
    }
}
catch (Exception exception)
{

}

using postman return similar error:

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/UploadRawMaterialData'.",
    "MessageDetail": "No action was found on the controller 'PurchaseOrder' that matches the request."
}

But if I use postman to call it like this, no issue:

http://localhost/ControlTower2WebAPI/api/PurchaseOrder/UploadRawMaterialData?rawMaterialSupplierData=test

What am I missing?

2
  • Your ajax and C# code are not calling the same method, try calling the same method from ajax and see if you get a 404 Commented Dec 10, 2018 at 9:10
  • 2
    Also it seems like you're missing the [FromBody] in the UploadRawMaterialData method signature Commented Dec 10, 2018 at 9:19

2 Answers 2

1

In your method signature for the UploadRawMaterialData method you are missing the [FromBody] attribute. All POST requests with data in the body need this

Sign up to request clarification or add additional context in comments.

Comments

1

You have two options,

  1. Use [FromBody] as suggested in other answer,
  2. Make your Url like this.

string queryData="test" string apiUrl="http://localhost/ControlTower2WebAPI/api/PurchaseOrder/UploadRawMaterialData?rawMaterialSupplierData="+test;

Basically, The way you are sending your query data is all that matters, If you don't specify [FromBody] attribute, the data is passed in the URI and URI has to be modified.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.