How to Migrate Existing Web API Controllers by Using a Compatibility Shim

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest

.NET and Microsoft decided to merge the MVC and Web API functionality, after the release of ASP.NET. If you are looking for the implementation of Web API with ASP.NET, Here is the way to accomplish:

Migrating Existing Web API Controllers by Compatibility Shim

You will have to alter one code to call AddWebApiConventions() if you use HttpResponseMessage in Web API controllers. It will help to know the proper serialize that response by wiring up the HttpResponseMessageOutputFormatter.

public void ConfigureServices(IServiceCollection services)
{
	// Add framework services.
	services.AddMvc().AddWebApiConventions(); //Add WebApi
}

}Depending upon your routing with Web API. You will need to register routes with Startup class.

In this way, you can migrate from your Web API code to ASP.NET Core. 

public void Configure(IApplicationBuilder app, 
                IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseMvc(routes =>
    {
	routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
    });
}

This sample controller helps you to use your ApiController within ASP.NET Core with compatibility Shim.

[Route("api/[controller]/[action]")]
public class ValuesApiController : ApiController
{
	[HttpGet]
	[ActionName("GetArray")]
	public IEnumerable GetArray()
	{
		//example returns a basic type that is automatically serialized as json - nothing special here
		return new string[] { "value2", "value3" };
	}

	[HttpGet]
	[ActionName("GetSomeJson")]
	public HttpResponseMessage GetSomeJson()
	{
		//example returns a HttpResponseMessage - the shim makes this possible
		var resp = new HttpResponseMessage()
		{
			Content = new StringContent("[{\"Name\":\"ABC\"},[{\"A\":\"1\"},{\"B\":\"2\"},{\"C\":\"3\"}]]")
		};

		resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
		return resp;
	}
}

 

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on whatsapp
Share on email

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recommended for you
Connect With Us
Stay Connected
Subscribe to our newsletter today to receive updates on latest tech news, tutorials SEO tips many more.
Latest Articles