0

I'd like to submit json from a controller in an MVC app to a Web API app.

In the Web API app, one of the controller methods takes a string:

//In ValuesController.cs
[HttpGet("{myjson}")]
public string Index (string myjson) {
  ...
}

If I try the url http://localhost/api/values/testing, it will go into:

[HttpGet("{id}")]
public string Get (int id) {
 ...
}

Which is also in ValuesController.cs.

Any ideas why the first method is not triggering?

2
  • Usually you post when you want to send something like json. I'm not quite sure I understand your question however. If you attribute the methods properly, you can deserialize (using json.net) into your class object. Commented May 6, 2015 at 20:19
  • Why don't you just pass it as a C# class instead of creating a JSON object and then passing it to a web api that takes a c# class? Commented May 6, 2015 at 20:25

4 Answers 4

2

You can build a URL that contains the properties of MyClass on the query string and invoke the remote client with HttpClient (or a third party option like RestSharp).

In addition, you need to mark your WebAPI endpoint method with [FromUri] so that it knows to expect a complex type from the query string rather than the request body.

[HttpGet("/")]
public string Index ([FromUri] MyClass aclass) {
    ...
}

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://.../");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var url = String.Format("api/ControllerName?ID={0}&Dept={1}", 
        myModel.ID, myModel.Dept);

    HttpResponseMessage response = await client.GetAsync(url);
    if (response.IsSuccessStatusCode)
    {
        MyModel model = await response.Content.ReadAsAsync<MyModel>();
    }
}

In this particular case you actually don't need to create a JSON string since you can pass all of the required data on the query string. If you don't want to expose the data, you should consider changing it to a post, at which point you can post the object directly.

...
response = await client.PostAsJsonAsync(url, myModel);
...
Sign up to request clarification or add additional context in comments.

Comments

1

Check out Json.NET by Newtonsoft. If you change your endpoint to accept a Stream, I think you can do something like this:

var myClass = new JsonSerializer()
                  .Deserialize<MyClass>(
                    new JsonTextReader(
                      new StreamReader(stream, Encoding.UTF8, false, 1, true)));

Comments

0

You can use a library to serialize and deserialize JSON into objects. Json.NET is pretty good at doing this.

Comments

0

You can use simple RestSharp client: http://restsharp.org

var client = new RestClient(" http://localhost/api/values");
var request = new RestRequest("", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new { Name = "Miroslav" });
RestResponse response = client.Execute(request);

I did not catch your controller structure, but you can update this example.

Documentation: https://github.com/restsharp/RestSharp/wiki

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.