Showing posts with label WebAPI. Show all posts
Showing posts with label WebAPI. Show all posts

Wednesday, January 18, 2017

WebAPI : Using Swagger and Postman with multiple POST

I've been busy on a WebAPI project where I need multiple POST actions in a a WebAPI controller.

There's a ton of stuff around best practice for this - some say each controller should only have one POST; others disagree.

I finally decided to break the controllers up by category and then within each controller have multiple POST functions.

I also added Swagger via Swashbuckle and used Postman for some unit tests so I thought I would write this all up.

As an example, I have a Maths controller with Add and Multiply.

The controller:

using MathsWebAPI.Models;
using System.Web.Http;

namespace MathsWebAPI.Controllers
{
    public class MathsController : ApiController
    {
        // POST: api/Maths
        [HttpPost]
        public int Add([FromBody] Maths info)
        {
            int number1 = info.number1;
            int number2 = info.number2;

            return (number1 + number2);
        }

        // POST: api/Maths
        [HttpPost]
        public int Multiply([FromBody] Maths info)
        {
            int number1 = info.number1;
            int number2 = info.number2;

            return (number1 * number2);
        }
    }
}

Note that I am passing in a model object as I have multiple parameters.

The model object:

namespace MathsWebAPI.Models
{
    public class Maths
    {
        public int number1 { get; set; }

        public int number2 { get; set; }
    }
}

The WebAPIConfig.cs:

using System.Web.Http;

namespace MathsWebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            /*config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );*/

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

In SwaggerConfig.cs, uncomment:

c.DisableValidator();

to avoid the error message.

Now if I navigate to:

http://localhost:44571/swagger

where 44571 is my IIS Express port

I see:


Now if you click the yellow area, it will populate the "Info" box with the model object format and you just have to fill in the values.

Click "Try it out" and you see:


 Note the URL is:

api/Maths/Add

Now if we add Postman, the commands are in this gist.

Running the script, we see:


Enjoy!

Thursday, March 31, 2016

ADFS - Native Client and Web API on Server 2016 TP4 ADFS 4.0

This follows on from my previous post concerning Web App and Web API.

This is for Active Directory Federation Services on Server 2016 Technical Preview 4.

The code is based on the Azure AD sample: Active directory .NET native desktop.

Just ignore all the Azure AD comments. There is no Azure in this solution.

In the solution, I've set the the web API to be at localhost:44324.

The native desktop client is built on WPF.

Just to re-iterate - the ADFS has to be Server 2016 - TP4 and above. This will not work on Server 2012 R2 - ADFS 3.0. 

As before, the changes are all in a gist here.

On to the ADFS configuration:

You need to create a new Application Group.


Create the Native Client


The Client Id needs to be copied over into "ida:ClientId" in the app.config.

Create the web API.


The rest of the configuration is exactly the same as the previous post.

Exactly the same claims rules are required.

You end up with a new application group.


Note in the gist that the code around scope has been commented out. I couldn't get the scope to be passed over.

I raised this in the TP4 forum.

Run up the sample, click "Sign In" in the WPF application and you should be redirected to ADFS for authentication.

Then you should be able to add items to the to-do list.

Enjoy!

Thursday, April 23, 2015

Postman : Testing ASP.NET MVC Webapi

I've been looking at Postman.

It's a way of easily testing REST API.

So to play around with it, I thought I would test it against the standard ASP.NET MVC webapi project using VS 2013.

So run up a ASP.NET MVC webapi VS project in the usual way. Under ValuesController.cs, you'll see the standard API calls.

// GET api/values
        public IEnumerable Get()
        {
            return new string[] { "value1", "value2" };
        }

So http://xxx/api/values will return an array of the two values above.

So let's try:


Notice we need to select "GET" from the drop-down. You see the values returned as expected. You can select the format i.e. this is JSON. The "Status" is "200 OK". If you hold the cursor over this, you get a description of what the status means. Neat!

OK, let's try a PUT.

I changed the code to look like:

// PUT api/values/5
        public String Put(int id, [FromBody]string value)
        {
            return ("ID was " + id + " value was " + value);
        }

Remember to select "PUT" in the drop-down. If you select "Preview", you'll see what the HTTP message that is sent is.

Notice we get the ID but not the value. There's a ton of stuff on the Internet on this particular subject.

So let's select the "Raw" button, select "Text" from the drop-down, type in some text and press "Send".

You get the "No MediaTypeFormatter is available" message.

You can fix this via C# – Supporting text/plain in an MVC 4 Web API application.

Go and add that - I'll wait.

All done? - let's proceed.


All A-OK!

Note: There is an Interceptor feature which you can add to Postman. Running my website locally, I could only get this to work with the Interceptor turned off. Otherwise, it just hangs.

Enjoy!

Tuesday, December 10, 2013

Azure : Azure Active Directory and Web API

Two new labels today - moving off on another tangent!

Vittorio wrote an excellent article Secure ASP.NET Web API with Windows Azure AD and Microsoft OWIN Components.

When I tried to do this, ran into two problems.

Firstly, we have a *&&^%^%%$ corporate proxy - I HATE them.

So had to add the following to the test client in the web.config or app.config:
system.net
defaultProxy enabled="true" useDefaultCredentials="true"
proxy bypassonlocal="True" usesystemdefault="True"
defaultProxy
system.net
Insert your own xml start / end format!

Secondly, got the error:

"System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure."

In Vittorio's example, he uses localhost for the web site as did I.

You have to ensure you have no certificate errors when you browse to localhost - you can check that in IE - the certificate box should NOT be red.

If it is, just click it and run the wizard to import it into the "CA Trusted Root" area.

Also, make sure that it has not expired!

Enjoy!