I need to make a simple webapi call to post method with string argument.
Below is the code I'm trying, but when the breakpoint is hit on the webapi method, the received value is null.
StringContent stringContent = new System.Net.Http.StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(url.ToString(), stringContent);
and server side code:
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
please help...
If you want to send a json to your Web API, the best option is to use a model binding feature, and use a Class, instead a string.
Create a model
public class MyModel
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
If you wont use the JsonProperty attribute, you can write property in lower case camel, like this
public class MyModel
{
public string firstName { get; set; }
}
Then change you action, change de parameter type to MyModel
[HttpPost]
public void Post([FromBody]MyModel value)
{
//value.FirstName
}
You can create C# classes automatically using Visual Studio, look this answer here Deserialize JSON into Object C#
I made this following test code
Web API Controller and View Model
using System.Web.Http;
using Newtonsoft.Json;
namespace WebApplication3.Controllers
{
public class ValuesController : ApiController
{
[HttpPost]
public string Post([FromBody]MyModel value)
{
return value.FirstName.ToUpper();
}
}
public class MyModel
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
}
Console client application
using System;
using System.Net.Http;
namespace Temp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter to continue");
Console.ReadLine();
DoIt();
Console.ReadLine();
}
private static async void DoIt()
{
using (var stringContent = new StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json"))
using (var client = new HttpClient())
{
try
{
var response = await client.PostAsync("http://localhost:52042/api/values", stringContent);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
}
}
}
Output
Enter to continue
"JOHN"
Alternative answer: You can leave your input parameter as string
[HttpPost]
public void Post([FromBody]string value)
{
}
, and call it with the C# httpClient as follows:
var kvpList = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("", "yo! r u dtf?")
};
FormUrlEncodedContent rqstBody = new FormUrlEncodedContent(kvpList);
string baseUrl = "http://localhost:60123"; //or "http://SERVERNAME/AppName"
string C_URL_API = baseUrl + "/api/values";
using (var httpClient = new HttpClient())
{
try
{
HttpResponseMessage resp = await httpClient.PostAsync(C_URL_API, rqstBody); //rqstBody is HttpContent
if (resp != null && resp.Content != null) {
var result = await resp.Content.ReadAsStringAsync();
//do whatevs with result
} else
//nothing returned.
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
For the record I tried the above and could not get it working!
I couldn't get it working because my API was in a separate project. Which is fine right? no, I was doing Dependency Injection into the controller while using the Startup class against the Base project.
You can resolve this by using the WebAPI's config and configuring Dependency Injection there with Unity. The below code works for me:
WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
RegisterUnity();
}
private static void RegisterUnity()
{
var container = new UnityContainer();
container.RegisterType<IIdentityRespository, IdentityRespository>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
I hope it helps others :-)
Related
I'm doing a simple backend with .Net Core that reads data from GET and POST, but I'm not finding how to read GET params neither POST. I have this, a simple Controller:
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly ILogger<TestController> _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
}
[HttpGet]
public string Get()
{
return "Test GET OK";
}
[HttpPost]
public string Post()
{
return "Test POST OK";
}
}
Client, a simple windows forms with net framework 4.6, is using HttpClient to sent http get request:
public async Task<string> GetAsyncHttpClient(string uri)
{
string responseBody = "";
try
{
UriBuilder builder = new UriBuilder(uri);
builder.Query = "name=testName";
HttpResponseMessage response = await client.GetAsync(builder.Uri);
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
}
catch (Exception e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
responseBody = "Error with GET operation, exception:\n" + e.ToString();
}
return responseBody;
}
And generated URL is like this:
http://localhost:5915/test?name=testName
Trust me that I've searched a lot and I didn't find how to read and iterate over GET params.
How should I do it?
Thanks!
Normally you would just add a parameter to your method:
[HttpGet]
public string Get(string name)
You can be explicit that it's a query string parameter like this:
[HttpGet]
public string Get([FromQuery]string name)
As for iterating the parameters, you'll have to use Request.Query:
foreach (KeyValuePair<string, StringValues> entry in Request.Query)
{
string key = entry.Key;
foreach (string value in entry.Value)
{
System.Diagnostics.Debug.WriteLine($"{key}={value}");
}
}
You'll need to add a using Microsoft.Extensions.Primitives; for the StringValues. The reason why it's StringValues is because you could have a URL like this: https://www.example.com/test?name=Brian&name=Jennifer, so you would end up with two values in the Query collection entry for "name".
I don't know exactly what you mean but if you just want to make a post or get request then you do it in your client like this:
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response =
await client.PostAsync("https://localhost:YOURPORT/Test?username=test", YOURCONTENT);
var cont = await response.Content.ReadAsStringAsync();
Console.WriteLine(cont);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
make sure you are using http or https accordingly you have to adjust the url as well
if you mean Query Params you can access them by adding this to the API:
[HttpPost]
public void Post([FromQuery] string username){
//do something
}
As I am new to WebAPI I have been experimenting with samples from the web. I have an ApiController based class which handles Post, Get, etc. From my client application, I can perform a Get and a Delete successfully but when I do a Post or a Put of a string, I can see the string value is null at the server and I get StatusCode 204, No Content at the client. Using Postman I can successfully do a Post or Put so it seems to be a problem with my client app.
Have tried basing the client on .Net 4.7.2 as well as .NET Core 2.2
Here is the entire controller class of my WebAPI program:
namespace WebApplication1.Controllers
{
public class ValuesController : ApiController
{
static List<string> strings = new List<string>()
{
"value0", "value1", "Value2"
};
// GET api/values
public IEnumerable<string> Get()
{
return strings;
}
// GET api/values/5
public string Get(int id)
{
return strings[id];
}
// POST api/values
public void Post([FromBody]string value)
{
strings.Add(value);
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
strings[id] = value;
}
// DELETE api/values/5
public void Delete(int id)
{
strings.RemoveAt(id);
}
}
}
Here is code from my client Program:
class Program
{
static HttpClient client = new HttpClient();
static void Main()
{
RunAsync().GetAwaiter().GetResult();
}
static async Task RunAsync()
{
client.BaseAddress = new Uri("http://localhost:56037/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var response = await client.PutAsJsonAsync($"api/values/2", new StringContent("zzz"));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
I set breakpoints in the Put and Post methods but the value of the string being passed is null, not the value I sent to the server.
Id maybe try
var response = await client.PutAsJsonAsync($"api/values/2", new StringContent("zzz"), System.Text.Encoding.UTF8, "application/json");
Turns out that I needed to enclose the string in quotes as follows:
var response = await client.PutAsync("api/values/0", "\"zzz\"", new StringTypeFormatter());
response = await client.PostAsync("api/values", "\"zzz\"", new StringTypeFormatter());
If you want the item at the index, try:
strings.ElementAt(id) = value;
This is my Web API and it works fine, I mean when i enter this URL on my browser:
http://localhost:18207/api/values/GetMyClass
I retrieve this result:
<MyClass>
<A>a</A>
<b>b</b>
</MyClass>
My codes:
public class MyClass
{
public MyClass()
{
this.A = "a";
this.b = "b";
}
public string A { get; set; }
public string b { get; set; }
}
public class ValuesController : ApiController
{
public MyClass GetMyClass()
{
return new MyClass();
}
}
I have another console application to use my Web API and want to know,
How can i have a complex or object type of MyClass?
Codes on my Console are below but it returns string type
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
MainAsync(args, cts.Token).Wait();
}
static async Task MainAsync(string[] args, CancellationToken token)
{
string baseAddress = "http://localhost:18207/api/values/GetMyClass";
using (var httpClient = new HttpClient())
{
string response = await httpClient.GetStringAsync(baseAddress);
}
}
Your response is probably coming to your console application as JSON (the reason your browser receives it as XML is because of different Accept headers, you can learn about that if you look at Content Negotiation). So what you need to do is parse the JSON and have it deserialize it into your object. There's quite a few libraries that can do that for you.
First make sure that your MyClass is defined in a Class Library project that both your Web API project and your Console project are referencing. This allows us to reuse the class definition without needing to have a separate copy in both projects.
Next, you need a JSON parsing library. There's one built into .NET, but there's a 3rd party one called Json.NET that is the gold standard. My answer will use that one since I'm more familiar with it. Install the Newtonsoft.Json package into your console app.
Then, change your console app as follows:
using Newtonsoft.Json; // at the top of your file
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
MainAsync(args, cts.Token).Wait();
}
static async Task MainAsync(string[] args, CancellationToken token)
{
string baseAddress = "http://localhost:18207/api/values/GetMyClass";
using (var httpClient = new HttpClient())
{
string json = await httpClient.GetStringAsync(baseAddress);
MyClass instance = JsonConvert.DeserializeObject<MyClass>(json);
}
}
The JsonConvert class handles serializing and deserializing the JSON. When deserializing, we just tell is which class to deserialize to and it will attempt to convert the JSON to an instance of that class and return it.
You can use method "GetAsync" which will return object of class "HttpResponseMessage" and then you can call "ReadAsAsync" on Content property.
Please see below code:
public class MyClass
{
public MyClass()
{
this.A = "a";
this.b = "b";
}
public string A { get; set; }
public string b { get; set; }
}
static void Main(string[] args)
{
var cts = new CancellationTokenSource();
MainAsync(args, cts.Token).Wait();
}
static async Task MainAsync(string[] args, CancellationToken token)
{
string baseAddress = "http://localhost:18207/api/values/GetMyClass";
using (var httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.GetAsync(baseAddress);
response.EnsureSuccessStatusCode();
MyClass result = await response.Content.ReadAsAsync< MyClass>();
}
}
Here is the full solution end-to-end. We are hosting a Web Api that returns MyClass and then we are calling the API and getting data formatted as XML through a console application.
First, we have MyClass annotated as a DataContract:
[DataContract]
public class MyClass
{
public MyClass()
{
this.A = "a";
this.b = "b";
}
[DataMember]
public string A { get; set; }
[DataMember]
public string b { get; set; }
}
The MyClass Web API:
[AllowAnonymous]
public class MyClassController : ApiController
{
public MyClass Get()
{
return new MyClass();
}
}
and a Console app that uses HttpWebRequest to call the Web Api.
Here's that code (the bottom half is from my original post):
static void Main(string[] args)
{
// this is my Web API Endpoint
var req = (HttpWebRequest)WebRequest.Create("http://localhost:17512/api/MyClass");
// default is JSON, but you can request XML
req.Accept = "application/xml";
req.ContentType = "application/xml";
var resp = req.GetResponse();
var sr = new StreamReader(resp.GetResponseStream());
// read the response stream as Text.
var xml = sr.ReadToEnd();
var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
// Deserialize
var ser = new XmlSerializer(typeof(MyClass));
var instance = (MyClass)ser.Deserialize(ms);
Console.WriteLine(instance.A);
Console.WriteLine(instance.b);
var final = Console.ReadLine();
}
NOTE: You'll need to figure out if you want to share a reference to MyClass between the two assemblies or if you just want to have a copy of the code file in each project.
You could just remove XML Formatter inside your WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Removing XML
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Allows us to map routes using [Route()] and [RoutePrefix()]
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Then in your controller you would return just like in your example:
public class ValuesController : ApiController
{
public MyClass GetMyClass()
{
return new MyClass();
}
}
UPDATE 1: I did my answer become more consistent with the question
When making a Request from a Console Application, you could use RestSharp.
var client = new RestClient("http://localhost:18207/");
var request = new RestRequest("api/values/GetMyClass", Method.GET);
var response = client.Execute<MyClass>(request);
if(response.StatusCode == HttpStatusCode.OK)
var responseData = response.Data;
When you execute client.Execute<MyClass>(request) it will deserialize the response into an object of that class. If field names match it should work.
I would like to return camel-cased JSON data using Web API. I inherited a mess of a project that uses whatever casing the previous programmer felt like using at the moment (seriously! all caps, lowercase, pascal-casing & camel-casing - take your pick!), so I can't use the trick of putting this in the WebApiConfig.cs file because it will break the existing API calls:
// Enforce camel-casing for the JSON objects being returned from API calls.
config.Formatters.OfType<JsonMediaTypeFormatter>().First().SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
So I'm using a custom class that uses the JSON.Net serializer. Here is the code:
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class JsonNetApiController : ApiController
{
public string SerializeToJson(object objectToSerialize)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
if (objectToSerialize != null)
{
return JsonConvert.SerializeObject(objectToSerialize, Formatting.None, settings);
}
return string.Empty;
}
}
The problem is that the raw data returned looks like this:
"[{\"average\":54,\"group\":\"P\",\"id\":1,\"name\":\"Accounting\"}]"
As you can see, the backslashes mess things up. Here is how I'm calling using the custom class:
public class Test
{
public double Average { get; set; }
public string Group { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
public class SomeController : JsonNetApiController
{
public HttpResponseMessage Get()
var responseMessage = new List<Test>
{
new Test
{
Id = 1,
Name = "Accounting",
Average = 54,
Group = "P",
}
};
return Request.CreateResponse(HttpStatusCode.OK, SerializeToJson(responseMessage), JsonMediaTypeFormatter.DefaultMediaType);
}
What can I do differently to get rid of the backslashes? Is there an alternative way to enforcing camel-casing?
Thanks to all the references to other Stackoverflow pages, I'm going to post three solutions so anyone else having a similar issue can take their pick of the code. The first code example is one that I created after looking at what other people were doing. The last two are from other Stackoverflow users. I hope this helps someone else!
// Solution #1 - This is my solution. It updates the JsonMediaTypeFormatter whenever a response is sent to the API call.
// If you ever need to keep the controller methods untouched, this could be a solution for you.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json.Serialization;
public class CamelCasedApiController : ApiController
{
public HttpResponseMessage CreateResponse(object responseMessageContent)
{
try
{
var httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, responseMessageContent, JsonMediaTypeFormatter.DefaultMediaType);
var objectContent = httpResponseMessage.Content as ObjectContent;
if (objectContent != null)
{
var jsonMediaTypeFormatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
};
httpResponseMessage.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, jsonMediaTypeFormatter);
}
return httpResponseMessage;
}
catch (Exception exception)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, exception.Message);
}
}
}
The second solution uses an attribute to decorate the API controller method.
// http://stackoverflow.com/questions/14528779/use-camel-case-serialization-only-for-specific-actions
// This code allows the controller method to be decorated to use camel-casing. If you can modify the controller methods, use this approach.
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;
using Newtonsoft.Json.Serialization;
public class CamelCasedApiMethodAttribute : ActionFilterAttribute
{
private static JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();
static CamelCasedApiMethodAttribute()
{
_camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public override void OnActionExecuted(HttpActionExecutedContext httpActionExecutedContext)
{
var objectContent = httpActionExecutedContext.Response.Content as ObjectContent;
if (objectContent != null)
{
if (objectContent.Formatter is JsonMediaTypeFormatter)
{
httpActionExecutedContext.Response.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, _camelCasingFormatter);
}
}
}
}
// Here is an example of how to use it.
[CamelCasedApiMethod]
public HttpResponseMessage Get()
{
...
}
The last solution uses an attribute to decorate the entire API controller.
// http://stackoverflow.com/questions/19956838/force-camalcase-on-asp-net-webapi-per-controller
// This code allows the entire controller to be decorated to use camel-casing. If you can modify the entire controller, use this approach.
using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using Newtonsoft.Json.Serialization;
public class CamelCasedApiControllerAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings httpControllerSettings, HttpControllerDescriptor httpControllerDescriptor)
{
var jsonMediaTypeFormatter = httpControllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
httpControllerSettings.Formatters.Remove(jsonMediaTypeFormatter);
jsonMediaTypeFormatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
};
httpControllerSettings.Formatters.Add(jsonMediaTypeFormatter);
}
}
// Here is an example of how to use it.
[CamelCasedApiController]
public class SomeController : ApiController
{
...
}
If you want to set it globally you can just remove the current Json formatter from the HttpConfiguration and replace it with your own.
public static void Register(HttpConfiguration config)
{
config.Formatters.Remove(config.Formatters.JsonFormatter);
var serializer = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var formatter = new JsonMediaTypeFormatter { Indent = true, SerializerSettings = serializer };
config.Formatters.Add(formatter);
}
Comment on https://stackoverflow.com/a/26506573/887092 works for some cases but not others
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
This way works in other cases
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
So, cover all bases with:
private void ConfigureWebApi(HttpConfiguration config)
{
//..
foreach (var jsonFormatter in config.Formatters.OfType<JsonMediaTypeFormatter>())
{
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
var singlejsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
singlejsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
This is a follow-up on an earlier question regarding using HttpClient with Web API performing authentication using a custom Message Handler.
I can request data from the server using the provided solution, but now I am having trouble posting JSON data to the server. Whenever I try posting data to the Web API I am returned an Internal Server Error response code.
Here is the code on the client side:
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage();
request.Headers.Add("X-Token", UserSession.GlobalInstance.SecurityToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(_apiBaseAddress + "api/User");
request.Content = new ObjectContent<UserDTO>(userDTO, new JsonMediaTypeFormatter());
var response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
// handle result code
}
throw new Exception(String.Format("Server generated error response: {0}", response.StatusCode));
}
The declaration for the controller method:
public class UserController : ApiController
{
public long Post(UserDTO userDTO)
{
// create user and return custom result
// code (e.g. success, duplicate email, etc...)
}
}
(I've also added [FromBody] to the method parameter, but end up with the same result).
A snapshot of the code for my message handler and routing configuration can be found here.
Your code works as expected...
The server side.
Create a console application and run NuGet
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
Program.cs
internal class Program
{
private static IDisposable _server;
private static void Main(string[] args)
{
_server = WebApp.Start<Startup>("http://localhost:12345");
Console.ReadLine();
_server.Dispose();
}
}
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var userTokenInspector = new UserTokenInspector {InnerHandler = new HttpControllerDispatcher(config)};
config.Routes.MapHttpRoute(
"UserAuthenticationApi",
"api/{controller}/Authenticate",
new {controller = "User", action = "Authenticate"},
null
);
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional},
null,
userTokenInspector
);
}
}
UserTokenInspector.cs
public class UserTokenInspector : DelegatingHandler {
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken) {
const string TOKEN_NAME = "X-Token";
if (!request.Headers.Contains(TOKEN_NAME)) {
return Task.FromResult(request.CreateErrorResponse(HttpStatusCode.Unauthorized,
"Request is missing authorization token."));
}
try {
//var token = UserToken.Decrypt(request.Headers.GetValues(TOKEN_NAME).First());
// validate token
// ...
// ...
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("alex"), new string[] { });
}
catch {
return Task.FromResult(request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid token."));
}
return base.SendAsync(request, cancellationToken);
}
}
UserController.cs
public class UserController : ApiController
{
public long Post(UserDTO userDTO)
{
// create user and return custom result
// code (e.g. success, duplicate email, etc...)
return 1;
}
}
UserDto.cs
public class UserDTO
{
public string Username { get; set; }
}
ValuesController.cs
public class ValuesController : ApiController
{
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, "yay");
}
}
The Client... create a Console application and run NuGet:
Install-Package Microsoft.AspNet.WebApi.Client
Program.cs
internal class Program
{
private static void Main(string[] args)
{
var request = new HttpRequestMessage();
request.Headers.Add("X-Token", "token");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Post;
var baseAddress = "http://localhost:12345/";
request.RequestUri = new Uri(baseAddress + "api/User");
var userDto = new UserDTO() {Username = "Alex"};
request.Content = new ObjectContent<UserDTO>(userDto, new JsonMediaTypeFormatter());
var httpClient = new HttpClient();
var response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
// handle result code
Console.WriteLine(response.StatusCode);
Console.ReadLine();
}
}
}